﻿using Serilog;
using System.Windows.Controls;
using System.Windows;
using System.Windows.Media;
using System.Windows.Threading;
using System.Collections.ObjectModel;
using System.Collections.Specialized;
using System.Windows.Documents;
using SimpleTool.SerialTool.SerialControl;
using System.Windows.Input;
using SimpleTool.Server;
using static SimpleTool.SerialTool.SerialControl.CommandSectionModel;
using System.Text.RegularExpressions;
using static SimpleTool.Server.Extendsion;
using SimpleTool.ActivityUnit;
using static SimpleTool.ActivityUnit.ActivitySectionModel;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.ComponentModel;
using SimpleTool.Base;
using System.Collections;
using System.Windows.Controls.Primitives;
using DynamicData;
using System.Reactive.Linq;
using CommunityToolkit.Mvvm.Messaging;
using System.Diagnostics;
using Microsoft.Extensions.DependencyInjection;


namespace SimpleTool.TransformComponent
{
    public class EnjoyTextBox : TextBox
    {

        public readonly ILogger Logger = Log.ForContext<EnjoyTextBox>();

        public CornerRadius CornerRadius
        {
            set
            {
                SetValue(CornerRadiusProperty, value);
            }
            get
            {
                return (CornerRadius)GetValue(CornerRadiusProperty);
            }
        }

        public static readonly DependencyProperty CornerRadiusProperty = DependencyProperty.Register(
            nameof(CornerRadius),
            typeof(CornerRadius),
            typeof(EnjoyTextBox));

        public Brush SelectionBGBrush
        {
            set
            {
                SetValue(SelectionBGBrushProperty, value);
            }
            get
            {
                return (Brush)GetValue(SelectionBGBrushProperty);
            }
        }

        public static readonly DependencyProperty SelectionBGBrushProperty = DependencyProperty.Register(
            nameof(SelectionBGBrush),
            typeof(Brush),
            typeof(EnjoyTextBox),
            new PropertyMetadata(Brushes.Black));

    }

    /// <summary>
    /// 自定义消息框类，提供以下静态方法
    /// <para>1. Show(string title, string message, bool result = true)</para>
    /// <para>2. Show(string title, int icon, List[string] options, string message)</para>
    /// <para>3. Show(string title, List[string] options, List[string] itemsSource, SelectionMode mode, List[int]? selects)</para>
    /// <para>4. Show(string title, List[string] options, ConfigOption option)</para>
    /// <para>5. Show(double minnum, double maxnum)</para>
    /// <para>6. Show(string title, List[string] options, Dictionary[string, string] args)</para>
    /// </summary>
    public class CustomMessageBox: Window
    {
        public static readonly ILogger Logger = Log.ForContext<CustomMessageBox>();

        private ConditionalWeakTable<string, WeakReference<FrameworkElement>> SubcripElementManager = [];

        private ConditionalWeakTable<string, WeakReference<Border>> SubcripBorderManager = [];

        private WeakReference<ListBox>? ListBoxWeak;

        private string SearchFlag = string.Empty;

        private readonly Dictionary<string, List<string>> SearchMatchMap = [];

        private Dictionary<string, string> SearchResultMap = [];

        private string MainEchoMessage = string.Empty;

        private string AssistMessage = string.Empty;

        private List<string> Options = ["否", "是"];

        /// <summary>
        /// <para>1. public List[string] selectedValues = [];</para>
        /// <para>2. public int index = -1;</para>
        /// <para>3. public string content = string.Empty;</para>
        /// </summary>
        public sealed class Invoke 
        {
            public List<string> selectedValues = [];

            public int index = -1;

            public string content = string.Empty;
        };

        /// <summary>
        /// <para>1. public string CurrentApplyDBaddress = string.Empty;</para>
        /// <para>2. public string CurrentApplyDBkey = string.Empty;</para>
        /// <para>3. public string CurrentApplyUnknown1 = string.Empty;</para>
        /// <para>3. public string CurrentApplyUnknown2 = string.Empty;</para>
        /// <para>3. public int index = -1;</para>
        /// </summary>
        public sealed class ConfigOption
        {
            public string CurrentApplyDBaddress = string.Empty;

            public string CurrentApplyDBkey = string.Empty;

            public string CurrentApplyUnknown1 = string.Empty;

            public string CurrentApplyUnknown2 = string.Empty;

            public int index = -1;
        };

        IActivityDetetorAssist ActivityDetetorServer;

        public sealed class Field
        {
            public string title = string.Empty;

            public string message = string.Empty;

            public int type = 0;

            public List<string> options = [];

            public List<string> itemsSource = [];
        };

        private static readonly Invoke InvokeOut = new ();

        private static readonly ConfigOption OptionOut = new();

        public CustomMessageBox()
        {
            FontFamily = "YaHei".FindSource<FontFamily>();
            this.FindVisualBtObject<Border>();
            MaxWidth = 360;
            MaxHeight = 266;
            App MyApp = (App)Application.Current;
            ActivityDetetorServer = MyApp.RetailSection.GetRequiredService<IActivityDetetorAssist>();
        }

        public static void Show(string title, string message, bool result = true)
        {
            Application.Current.Dispatcher.Invoke(() =>
            {
                CustomMessageBox messageBox = new()
                {
                    BorderThickness = new Thickness(1),
                    BorderBrush = "Driftwood".FindSolidBrush(),
                    Owner = Application.Current.MainWindow,
                    WindowStartupLocation = WindowStartupLocation.CenterOwner,
                    WindowStyle = WindowStyle.None,
                    ResizeMode = ResizeMode.NoResize,
                    ShowInTaskbar = false,
                    Topmost = true,
                    MaxHeight = 186
                };

                Grid mainGrid = new()
                {
                    Background = "MoonlitLavender".FindSolidBrush(),
                    HorizontalAlignment = HorizontalAlignment.Stretch,
                    VerticalAlignment = VerticalAlignment.Stretch
                };

                mainGrid.RowDefinitions.Add(new RowDefinition() { Height = new GridLength(42) });
                mainGrid.RowDefinitions.Add(new RowDefinition() { Height = new GridLength(1, GridUnitType.Star) });
                mainGrid.RowDefinitions.Add(new RowDefinition() { Height = GridLength.Auto });

                Grid TitleGrid = new()
                {
                    Margin = new Thickness(4, 4, 3, 7),
                    VerticalAlignment = VerticalAlignment.Center
                };

                TitleGrid.ColumnDefinitions.Add(new ColumnDefinition() { Width = new GridLength(42) });
                TitleGrid.ColumnDefinitions.Add(new ColumnDefinition() { Width = new GridLength(1, GridUnitType.Star) });

                TextBlock HintIcon = new()
                {
                    FontFamily = "Icon".FindSource<FontFamily>(),
                    Margin = new Thickness(0, 0, 5, 0),
                    VerticalAlignment = VerticalAlignment.Center,
                    FontSize = 30.0,
                };

                TextBlock Title = new()
                {
                    Text = title,
                    Foreground = "DeepMatrix".FindSolidBrush(),
                    FontSize = 16,
                    VerticalAlignment = VerticalAlignment.Center,
                    TextAlignment = TextAlignment.Left,
                    HorizontalAlignment = HorizontalAlignment.Left,
                    Margin = new Thickness(0, 0, 3, 0)
                };
                TitleGrid.SetGridWidget(0, 0, HintIcon);
                TitleGrid.SetGridWidget(0, 1, Title);

                TextBlock MessageTextBlock = new()
                {
                    Text = message,
                    FontSize = 24.0,
                    FontWeight = FontWeight.FromOpenTypeWeight(500),
                    Padding = new Thickness(5),
                    TextAlignment = TextAlignment.Center,
                    VerticalAlignment = VerticalAlignment.Center,
                };

                if (result)
                {
                    HintIcon.Text = "\ue603";
                    HintIcon.Foreground = "JadeFlow".FindSolidBrush();
                    MessageTextBlock.Foreground = "JadeFlow".FindSolidBrush();
                }
                else
                {
                    HintIcon.Text = "\ue605";
                    HintIcon.Foreground = "SunsetCoral".FindSolidBrush();
                    MessageTextBlock.Foreground = "SunsetCoral".FindSolidBrush();
                }

                mainGrid.SetGridWidget(0, 0, TitleGrid);
                mainGrid.SetGridWidget(1, 0, MessageTextBlock);

                DispatcherTimer? closeTimer = null;
                closeTimer  = new DispatcherTimer(
                                  TimeSpan.FromMilliseconds(2500),
                                  DispatcherPriority.Normal, // 改为 DispatcherPriority.SystemIdle
                                  (s, e) =>
                                  {
                                      closeTimer?.Stop();
                                      messageBox.Close();
                                  },
                                  Application.Current.Dispatcher);
                
                messageBox.AddChild(mainGrid);
                messageBox.ShowDialog();
            });
        }

        public static Invoke Show(string title, int icon, List<string> options, string message)
        {
            Application.Current.Dispatcher.Invoke(() =>
            {
                CustomMessageBox messageBox = new()
                {
                    BorderThickness = new Thickness(1),
                    BorderBrush = "Driftwood".FindSolidBrush(),
                    Owner = Application.Current.MainWindow,
                    WindowStartupLocation = WindowStartupLocation.CenterOwner,
                    WindowStyle = WindowStyle.None,
                    ResizeMode = ResizeMode.NoResize,
                    ShowInTaskbar = false,
                    Topmost = true,
                    MaxHeight = 186
                };

                Grid mainGrid = new()
                {
                    Background = "MoonlitLavender".FindSolidBrush(),
                    HorizontalAlignment = HorizontalAlignment.Stretch,
                    VerticalAlignment = VerticalAlignment.Stretch
                };

                mainGrid.RowDefinitions.Add(new RowDefinition() { Height = new GridLength(42) });
                mainGrid.RowDefinitions.Add(new RowDefinition() { Height = new GridLength(1, GridUnitType.Star) });
                mainGrid.RowDefinitions.Add(new RowDefinition() { Height = GridLength.Auto });

                Grid TitleGrid = new()
                {
                    Margin = new Thickness(4, 4, 3, 7),
                    VerticalAlignment = VerticalAlignment.Center
                };

                TitleGrid.ColumnDefinitions.Add(new ColumnDefinition() { Width = new GridLength(42) });
                TitleGrid.ColumnDefinitions.Add(new ColumnDefinition() { Width = new GridLength(1, GridUnitType.Star) });

                TextBlock HintIcon = new()
                {
                    FontFamily = "Icon".FindSource<FontFamily>(),
                    Margin = new Thickness(0, 0, 5, 0),
                    VerticalAlignment = VerticalAlignment.Center,
                    FontSize = 30.0,
                };

                TextBlock Title = new()
                {
                    Text = title,
                    FontFamily = "Icon".FindSource<FontFamily>(),
                    Foreground = "DeepMatrix".FindSolidBrush(),
                    FontSize = 16,
                    VerticalAlignment = VerticalAlignment.Center,
                    TextAlignment = TextAlignment.Left,
                    HorizontalAlignment = HorizontalAlignment.Left,
                    Margin = new Thickness(0, 0, 3, 0)
                };

                TitleGrid.SetGridWidget(0, 0, HintIcon);
                TitleGrid.SetGridWidget(0, 1, Title);

                switch (icon)
                {
                    case 0:
                        HintIcon.Text = "\ue607";
                        HintIcon.Foreground = "JadeFlow".FindSolidBrush();
                        break;
                    case 1:
                        HintIcon.Text = "\ue604";
                        HintIcon.Foreground = "MustardPop".FindSolidBrush();
                        break;
                    case 2:
                        HintIcon.Text = "\ue662";
                        HintIcon.Foreground = "SunsetCoral".FindSolidBrush();
                        break;
                }

                EnjoyRichTextBox MessageTextBox = new()
                {
                    IsReadOnly = true,
                    FontFamily = "Icon".FindSource<FontFamily>(),
                    FontSize = 14.0,
                    Padding = new Thickness(5),
                    Foreground = "DeepMatrix".FindSolidBrush(),
                    Background = "MoonlitLavender".FindSolidBrush(),
                    Style = "RichTextBox".FindSource<Style>(),
                    HorizontalContentAlignment = HorizontalAlignment.Center,
                    VerticalContentAlignment = VerticalAlignment.Center,
                    BorderBrush = Brushes.Transparent
                };

                MessageTextBox.AppendToEnd(message);

                Grid bottonGrid = new()
                {
                    MinHeight = 30.0,
                    HorizontalAlignment = HorizontalAlignment.Stretch,
                    VerticalAlignment = VerticalAlignment.Stretch,
                    Margin = new Thickness(5, 5, 5, 5)
                };

                int column = 0;
                foreach (var button in options)
                {
                    bottonGrid.ColumnDefinitions.Add(new ColumnDefinition() { Width = new GridLength(1, GridUnitType.Star) });
                    VariantButton variant = new VariantButton()
                    {
                        Content = button,
                        FontFamily = "YaHei".FindSource<FontFamily>(),
                        FontSize = 13.0,
                        Foreground = "DeepMatrix".FindSolidBrush(),
                        Margin = new Thickness(5, 0, 5, 0),
                        MinWidth = 110.0,
                        MinHeight = 28,
                        HorizontalAlignment = HorizontalAlignment.Center
                    };
                    bottonGrid.SetGridWidget(0, column, variant);
                    messageBox.SubcripElementManager.Add(button, new WeakReference<FrameworkElement>(variant));
                    variant.PreviewMouseUp += messageBox.ButtonClick;
                    column++;

                }
                mainGrid.SetGridWidget(0, 0, TitleGrid);
                mainGrid.SetGridWidget(1, 0, MessageTextBox);
                mainGrid.SetGridWidget(2, 0, bottonGrid);

                messageBox.AddChild(mainGrid);

                messageBox.ShowDialog();
                messageBox.DisposeSubcription();
                
            });
            return CustomMessageBox.InvokeOut;
        }

        public static Invoke Show(string title, List<string> options, List<string> itemsSource, SelectionMode mode = SelectionMode.Single, List<int>? selects = default)
        {
            Application.Current.Dispatcher.Invoke(() =>
            {
                CustomMessageBox messageBox = new()
                {
                    BorderThickness = new Thickness(1),
                    BorderBrush = "Driftwood".FindSolidBrush(),
                    Owner = Application.Current.MainWindow,
                    WindowStartupLocation = WindowStartupLocation.CenterOwner,
                    WindowStyle = WindowStyle.None,
                    ResizeMode = ResizeMode.NoResize,
                    ShowInTaskbar = false,
                    Topmost = true
                };

                Grid mainGrid = new()
                {
                    Background = "MoonlitLavender".FindSolidBrush(),
                    HorizontalAlignment = HorizontalAlignment.Stretch,
                    VerticalAlignment = VerticalAlignment.Stretch
                };

                mainGrid.RowDefinitions.Add(new RowDefinition() { Height = new GridLength(40) });
                mainGrid.RowDefinitions.Add(new RowDefinition() { Height = new GridLength(1, GridUnitType.Star) });
                mainGrid.RowDefinitions.Add(new RowDefinition() { Height = GridLength.Auto });

                Grid TitleGrid = new()
                {
                    Margin = new Thickness(4, 4, 3, 7),
                    VerticalAlignment = VerticalAlignment.Center
                };

                TitleGrid.ColumnDefinitions.Add(new ColumnDefinition() { Width = new GridLength(40) });
                TitleGrid.ColumnDefinitions.Add(new ColumnDefinition() { Width = new GridLength(1, GridUnitType.Star) });

                TextBlock HintIcon = new()
                {
                    Text = "\ue607",
                    Foreground = "JadeFlow".FindSolidBrush(),
                    FontFamily = "Icon".FindSource<FontFamily>(),
                    Margin = new Thickness(0, 0, 5, 0),
                    FontSize = 30.0,
                };

                TextBlock Title = new()
                {
                    Text = title,
                    FontFamily = "Icon".FindSource<FontFamily>(),
                    Foreground = "DeepMatrix".FindSolidBrush(),
                    FontSize = 16,
                    VerticalAlignment = VerticalAlignment.Center,
                    TextAlignment = TextAlignment.Left,
                    HorizontalAlignment = HorizontalAlignment.Left,
                    Margin = new Thickness(0, 0, 3, 0)
                };

                TitleGrid.SetGridWidget(0, 0, HintIcon);
                TitleGrid.SetGridWidget(0, 1, Title);

                ListBox MessageListBox = new()
                {
                    FontFamily = "YaHei".FindSource<FontFamily>(),
                    FontSize = 12.0,
                    SelectionMode = mode,
                    Style = "ListBoxTemplate".FindSource<Style>(),
                    BorderThickness = new Thickness(0),
                    Foreground = "DeepMatrix".FindSolidBrush(),
                    HorizontalContentAlignment = HorizontalAlignment.Left,
                    VerticalContentAlignment = VerticalAlignment.Center,
                };

                MessageListBox.ItemsSource = itemsSource;
                if (selects is null)
                {
                    MessageListBox.SelectedIndex = 0;
                }
                else
                {
                    if (mode == SelectionMode.Extended || mode == SelectionMode.Extended)
                    {
                        foreach (var index in selects)
                        {
                            DependencyObject dependency = MessageListBox.ItemContainerGenerator.ContainerFromIndex(index);
                            if (dependency is ListBoxItem item)
                            {
                                item.IsSelected = true;
                            }
                        }
                    }
                    else
                    {
                        MessageListBox.SelectedIndex = 0;
                    }
                }

                Grid bottonGrid = new()
                {
                    MinHeight = 30.0,
                    HorizontalAlignment = HorizontalAlignment.Stretch,
                    VerticalAlignment = VerticalAlignment.Stretch,
                    Margin = new Thickness(5, 5, 5, 5)
                };

                int column = 0;
                foreach (var button in options)
                {
                    bottonGrid.ColumnDefinitions.Add(new ColumnDefinition() { Width = new GridLength(1, GridUnitType.Star) });
                    VariantButton variant = new VariantButton()
                    {
                        Content = button,
                        FontFamily = "YaHei".FindSource<FontFamily>(),
                        FontSize = 11.0,
                        Foreground = "DeepMatrix".FindSolidBrush(),
                        Margin = new Thickness(5, 0, 5, 0),
                        MinWidth = 100.0,
                        MinHeight = 25
                    };
                    bottonGrid.SetGridWidget(0, column, variant);
                    messageBox.SubcripElementManager.Add(button, new WeakReference<FrameworkElement>(variant));
                    variant.PreviewMouseUp += messageBox.ButtonClick;
                    column++;

                }
                mainGrid.SetGridWidget(0, 0, TitleGrid);
                mainGrid.SetGridWidget(1, 1, MessageListBox);
                mainGrid.SetGridWidget(2, 0, bottonGrid);

                messageBox.AddChild(mainGrid);

                messageBox.ShowDialog();
                messageBox.DisposeSubcription();

                List<string> SelectItems = [];
                foreach(var select in MessageListBox.SelectedItems)
                {
                    if (select is not null) SelectItems.Add(select.GetSafetyChar());
                }
                Logger.DebudElite(SelectItems.Join(" "));
                CustomMessageBox.InvokeOut.selectedValues = SelectItems;
            });
            return CustomMessageBox.InvokeOut;
        }

        public static ConfigOption Show(string title, List<string> options, ConfigOption option)
        {

            Application.Current.Dispatcher.Invoke(() =>
            {
                CustomMessageBox messageBox = new()
                {
                    BorderThickness = new Thickness(1),
                    BorderBrush = "Driftwood".FindSolidBrush(),
                    Owner = Application.Current.MainWindow,
                    WindowStartupLocation = WindowStartupLocation.CenterOwner,
                    WindowStyle = WindowStyle.None,
                    ResizeMode = ResizeMode.NoResize,
                    ShowInTaskbar = false,
                    Topmost = true,
                    MaxWidth = 500,
                    MaxHeight = 370
                };

                Grid mainGrid = new()
                {
                    Background = "MoonlitLavender".FindSolidBrush(),
                    HorizontalAlignment = HorizontalAlignment.Stretch,
                    VerticalAlignment = VerticalAlignment.Stretch
                };

                mainGrid.RowDefinitions.Add(new RowDefinition() { Height = new GridLength(40) });
                mainGrid.RowDefinitions.Add(new RowDefinition() { Height = new GridLength(1, GridUnitType.Star) });
                mainGrid.RowDefinitions.Add(new RowDefinition() { Height = GridLength.Auto });

                Grid TitleGrid = new()
                {
                    Margin = new Thickness(4, 4, 3, 7),
                    VerticalAlignment = VerticalAlignment.Center,
                    Height = 48.0
                };

                TitleGrid.ColumnDefinitions.Add(new ColumnDefinition() { Width = new GridLength(40) });
                TitleGrid.ColumnDefinitions.Add(new ColumnDefinition() { Width = new GridLength(1, GridUnitType.Star) });

                TextBlock HintIcon = new()
                {
                    Text = "\ue607",
                    Foreground = "JadeFlow".FindSolidBrush(),
                    FontFamily = "Icon".FindSource<FontFamily>(),
                    Margin = new Thickness(0, 0, 5, 0),
                    VerticalAlignment = VerticalAlignment.Center,
                    FontSize = 28.0,
                };

                TextBlock Title = new()
                {
                    Text = title,
                    FontFamily = "Icon".FindSource<FontFamily>(),
                    Foreground = "DeepMatrix".FindSolidBrush(),
                    FontSize = 16,
                    VerticalAlignment = VerticalAlignment.Center,
                    TextAlignment = TextAlignment.Left,
                    HorizontalAlignment = HorizontalAlignment.Left,
                    Margin = new Thickness(0, 0, 3, 0)
                };

                TitleGrid.SetGridWidget(0, 0, HintIcon);
                TitleGrid.SetGridWidget(0, 1, Title);

                Grid mainContentGrid = new()
                {
                    Margin = new Thickness(12),
                    Background = "MoonlitLavender".FindSolidBrush(),
                    VerticalAlignment = VerticalAlignment.Center,
                    HorizontalAlignment = HorizontalAlignment.Stretch,
                };

                mainContentGrid.ColumnDefinitions.Add(new ColumnDefinition() { Width = new GridLength(80) });
                mainContentGrid.ColumnDefinitions.Add(new ColumnDefinition() { Width = new GridLength(1, GridUnitType.Star) });

                mainContentGrid.RowDefinitions.Add(new RowDefinition() { Height = new GridLength(56) });
                mainContentGrid.RowDefinitions.Add(new RowDefinition() { Height = new GridLength(56) });
                mainContentGrid.RowDefinitions.Add(new RowDefinition() { Height = new GridLength(50) });
                mainContentGrid.RowDefinitions.Add(new RowDefinition() { Height = new GridLength(50) });

                TextBlock DBhint = new()
                {
                    Text = "数据库切换",
                    TextAlignment = TextAlignment.Center,
                    Foreground = "PineTrail".FindSolidBrush(),
                    VerticalAlignment = VerticalAlignment.Center
                };

                TextBlock unknown1 = new()
                {
                    Text = "未知配置",
                    TextAlignment = TextAlignment.Center,
                    Margin = new Thickness(0, 4, 0, 4),
                    Foreground = "PineTrail".FindSolidBrush(),
                    VerticalAlignment = VerticalAlignment.Center
                };

                TextBlock unknown2 = new()
                {
                    Text = "未知配置",
                    TextAlignment = TextAlignment.Center,
                    Margin = new Thickness(0, 4, 0, 4),
                    Foreground = "PineTrail".FindSolidBrush(),
                    VerticalAlignment = VerticalAlignment.Center
                };

                ComboBox DBAddressSelect = new()
                {
                    ItemsSource = new List<string>() { "云数据库", "本地数据库" },
                    SelectedValue = option.CurrentApplyDBaddress,
                    Height = 32,
                    IsEditable = true,
                    Margin = new Thickness(0, 4, 0, 4),
                    VerticalAlignment = VerticalAlignment.Center,
                    VerticalContentAlignment = VerticalAlignment.Center,
                    HorizontalContentAlignment = HorizontalAlignment.Center,
                    HorizontalAlignment = HorizontalAlignment.Stretch
                };

                ComboBox DBPasswordSelect = new()
                {
                    ItemsSource = new List<string>() { "云数据库", "Auto" },
                    SelectedValue = option.CurrentApplyDBkey,
                    Height = 32,
                    IsEditable = true,
                    Margin = new Thickness(0, 4, 0, 4),
                    VerticalAlignment = VerticalAlignment.Center,
                    VerticalContentAlignment = VerticalAlignment.Center,
                    HorizontalContentAlignment = HorizontalAlignment.Center,
                    HorizontalAlignment = HorizontalAlignment.Stretch
                };

                ComboBox unknownselect1 = new()
                {
                    ItemsSource = new List<string>() { "1", "2" },
                    SelectedValue = option.CurrentApplyUnknown1,
                    IsEditable = true,
                    Margin = new Thickness(0, 4, 0, 4),
                    VerticalAlignment = VerticalAlignment.Center,
                    VerticalContentAlignment = VerticalAlignment.Center,
                    HorizontalContentAlignment = HorizontalAlignment.Center,
                    HorizontalAlignment = HorizontalAlignment.Stretch
                };

                ComboBox unknownselect2 = new()
                {
                    ItemsSource = new List<string>() { "1", "2" },
                    SelectedValue = option.CurrentApplyUnknown2,
                    IsEditable = true,
                    Margin = new Thickness(0, 4, 0, 4),
                    VerticalAlignment = VerticalAlignment.Center,
                    VerticalContentAlignment = VerticalAlignment.Center,
                    HorizontalContentAlignment = HorizontalAlignment.Center,
                    HorizontalAlignment = HorizontalAlignment.Stretch
                };

                mainContentGrid.SetGridWidget(0, 0, 2, 0, DBhint);
                mainContentGrid.SetGridWidget(0, 1, DBAddressSelect);
                mainContentGrid.SetGridWidget(1, 1, DBPasswordSelect);
                mainContentGrid.SetGridWidget(2, 0, unknown1);
                mainContentGrid.SetGridWidget(2, 1, unknownselect1);
                mainContentGrid.SetGridWidget(3, 0, unknown2);
                mainContentGrid.SetGridWidget(3, 1, unknownselect2);

                int column = 0;
                Grid bottonGrid = new()
                {
                    MinHeight = 30.0,
                    HorizontalAlignment = HorizontalAlignment.Stretch,
                    VerticalAlignment = VerticalAlignment.Stretch,
                    Margin = new Thickness(5, 5, 5, 5)
                };
                foreach (var button in options)
                {
                    bottonGrid.ColumnDefinitions.Add(new ColumnDefinition() { Width = new GridLength(1, GridUnitType.Star) });
                    VariantButton variant = new VariantButton()
                    {
                        Content = button,
                        FontFamily = "YaHei".FindSource<FontFamily>(),
                        FontSize = 11.0,
                        Foreground = "DeepMatrix".FindSolidBrush(),
                        Margin = new Thickness(5, 0, 5, 0),
                        MinWidth = 100.0,
                        MinHeight = 25
                    };
                    bottonGrid.SetGridWidget(0, column, variant);
                    messageBox.SubcripElementManager.Add(button, new WeakReference<FrameworkElement>(variant));
                    variant.PreviewMouseUp += messageBox.ButtonClick;
                    column++;

                }
                mainGrid.SetGridWidget(0, 0, TitleGrid);
                mainGrid.SetGridWidget(1, 1, mainContentGrid);
                mainGrid.SetGridWidget(2, 0, bottonGrid);

                messageBox.AddChild(mainGrid);

                messageBox.ShowDialog();
                messageBox.DisposeSubcription();


                CustomMessageBox.OptionOut.CurrentApplyDBaddress = DBAddressSelect.SelectedValue.GetSafetyChar();
                CustomMessageBox.OptionOut.CurrentApplyDBkey = DBPasswordSelect.SelectedValue.GetSafetyChar();
                CustomMessageBox.OptionOut.CurrentApplyUnknown1 = unknownselect1.SelectedValue.GetSafetyChar();
                CustomMessageBox.OptionOut.CurrentApplyUnknown2 = unknownselect2.SelectedValue.GetSafetyChar();

            });
            return CustomMessageBox.OptionOut;
        }

        public static Action<double, string?> Show(double minnum, double maxnum, int delay = 2500)
        {
            CustomMessageBox? messageBox = null;
            ProgressBar? Prograss = null;
            TextBlock? HintBlock = null;

            Application.Current.Dispatcher.InvokeAsync(() =>
            {
                messageBox = new()
                {
                    Owner = Application.Current.MainWindow,
                    WindowStartupLocation = WindowStartupLocation.CenterOwner,
                    ResizeMode = ResizeMode.NoResize,
                    WindowStyle = WindowStyle.None,
                    AllowsTransparency = true,
                    Background = Brushes.Transparent,
                    ShowInTaskbar = false,
                    Topmost = true,
                    MaxHeight = 88,
                };

                Grid mainGrid = new()
                {
                    HorizontalAlignment = HorizontalAlignment.Stretch,
                    VerticalAlignment = VerticalAlignment.Center
                };

                mainGrid.RowDefinitions.Add(new RowDefinition() { Height = new GridLength(20) });
                mainGrid.RowDefinitions.Add(new RowDefinition() { Height = new GridLength(30) });

                HintBlock = new()
                {
                    FontFamily = "YaHei".FindSource<FontFamily>(),
                    Foreground = "DeepMatrix".FindSolidBrush(),
                    FontSize = 15,
                    VerticalAlignment = VerticalAlignment.Center,
                    TextAlignment = TextAlignment.Center,
                    HorizontalAlignment = HorizontalAlignment.Center,
                };

                Prograss = new()
                {
                    Background = "ArcticMist".FindSolidBrush(),
                    Margin = new Thickness(0, 8, 0, 0),
                    Minimum = minnum,
                    Maximum = maxnum,
                    Value = minnum,
                };

                mainGrid.SetGridWidget(0, 0, HintBlock);
                mainGrid.SetGridWidget(1, 0, Prograss);

                Border GridBorder = new()
                {
                    Background = "SunsetCoral".FindSolidBrush(),
                    CornerRadius = new CornerRadius(7),
                    Padding = new Thickness(8, 2, 8, 2),
                    Child = mainGrid
                };

                messageBox.Content = GridBorder;

                messageBox.Show();

            });
            return (_processValue, hint) =>
            {
                Application.Current.Dispatcher.BeginInvoke(async () =>
                {
                    if (Prograss is not null && messageBox is not null && HintBlock is not null)
                    {
                        if (Math.Abs(Prograss.Value - _processValue) >= 2 || _processValue >= 100.0)
                        {
                            Prograss.Value = _processValue;
                        }

                        if (hint is not null) HintBlock.Text = hint;

                        if (_processValue >= maxnum)
                        {
                            await Task.Delay(1000);
                            if (_processValue >= maxnum)
                            {
                                await Task.Delay(delay);
                                messageBox.Close();
                            }
                        }
                    }
                }, System.Windows.Threading.DispatcherPriority.Background);
            };
        }

        public static async Task<(int, Dictionary<string, string>?)> Show(string title, List<string> options, Dictionary<string, string> args)
        {
            CustomMessageBox? messageBox = null;
            await Application.Current.Dispatcher.InvokeAsync(() =>
            {
                messageBox = new()
                {
                    BorderThickness = new Thickness(1),
                    BorderBrush = "Driftwood".FindSolidBrush(),
                    Owner = Application.Current.MainWindow,
                    WindowStartupLocation = WindowStartupLocation.CenterOwner,
                    WindowStyle = WindowStyle.None,
                    ResizeMode = ResizeMode.NoResize,
                    ShowInTaskbar = false,
                    Topmost = true,
                    MaxWidth = 450,
                    MaxHeight = 520
                };

                Grid mainGrid = new()
                {
                    Background = "MoonlitLavender".FindSolidBrush(),
                    HorizontalAlignment = HorizontalAlignment.Stretch,
                    VerticalAlignment = VerticalAlignment.Stretch
                };

                mainGrid.RowDefinitions.Add(new RowDefinition() { Height = new GridLength(40) });
                mainGrid.RowDefinitions.Add(new RowDefinition() { Height = new GridLength(2, GridUnitType.Star) });
                mainGrid.RowDefinitions.Add(new RowDefinition() { Height = GridLength.Auto });
                mainGrid.RowDefinitions.Add(new RowDefinition() { Height = new GridLength(40) });

                Grid TitleGrid = new()
                {
                    Margin = new Thickness(4, 4, 3, 7),
                    VerticalAlignment = VerticalAlignment.Center,
                    Height = 48.0
                };

                TitleGrid.ColumnDefinitions.Add(new ColumnDefinition() { Width = new GridLength(40) });
                TitleGrid.ColumnDefinitions.Add(new ColumnDefinition() { Width = new GridLength(1, GridUnitType.Star) });

                TextBlock HintIcon = new()
                {
                    Text = "\ue607",
                    Foreground = "JadeFlow".FindSolidBrush(),
                    FontFamily = "Icon".FindSource<FontFamily>(),
                    Margin = new Thickness(0, 0, 5, 0),
                    VerticalAlignment = VerticalAlignment.Center,
                    FontSize = 28.0,
                };

                TextBlock Title = new()
                {
                    Text = title,
                    FontFamily = "Icon".FindSource<FontFamily>(),
                    Foreground = "DeepMatrix".FindSolidBrush(),
                    FontSize = 16,
                    VerticalAlignment = VerticalAlignment.Center,
                    TextAlignment = TextAlignment.Left,
                    HorizontalAlignment = HorizontalAlignment.Left,
                    Margin = new Thickness(0, 0, 3, 0)
                };

                TitleGrid.SetGridWidget(0, 0, HintIcon);
                TitleGrid.SetGridWidget(0, 1, Title);

                Grid mainContentGrid = new()
                {
                    Name = "ContentLayout",
                    Margin = new Thickness(12, 1, 12, 1),
                    Background = "MoonlitLavender".FindSolidBrush(),
                    VerticalAlignment = VerticalAlignment.Center,
                    HorizontalAlignment = HorizontalAlignment.Stretch,
                };

                mainContentGrid.ColumnDefinitions.Add(new ColumnDefinition() { Width = new GridLength(80) });
                mainContentGrid.ColumnDefinitions.Add(new ColumnDefinition() { Width = new GridLength(1, GridUnitType.Star) });
                mainContentGrid.ColumnDefinitions.Add(new ColumnDefinition() { Width = new GridLength(35) });

                if (!args.ContainsKey("BLUE")) args.Add("BLUE", string.Empty);
                if (!args.ContainsKey("DOID")) args.Add("DOID", string.Empty);

                int _irow = 0;
                foreach (var _map in ActivityAssistBehivor.Behivor.ParamReserveDutyMap.OrderBy(x => x.Value.Item2))
                {
                    string _name = string.Empty;
                    if (args.TryGetValue(_map.Key, out string? content)) _name = content;

                    mainContentGrid.RowDefinitions.Add(new RowDefinition() { Height = new GridLength(36) });

                    TextBlock ParamName = new()
                    {
                        TextAlignment = TextAlignment.Center,
                        FontSize = 16,
                        Foreground = "PineTrail".FindSolidBrush(),
                        VerticalAlignment = VerticalAlignment.Center
                    };

                    if (ActivityAssistBehivor.Behivor.ParamReserveDutyMap.TryGetValue(_map.Key, out (string, int) translate))
                    {
                        ParamName.Text = translate.Item1;
                    }

                    EnjoyTextBox ParamContent = new()
                    {
                        Text = _name,
                        Name = _map.Key,
                        Height = 35.0,
                        Margin = new Thickness(3, 0, 3, 0),
                        VerticalAlignment = VerticalAlignment.Center,
                        VerticalContentAlignment = VerticalAlignment.Center,
                        HorizontalContentAlignment = HorizontalAlignment.Center,
                        HorizontalAlignment = HorizontalAlignment.Stretch
                    };

                    messageBox.SubcripElementManager.Add(_map.Key, new WeakReference<FrameworkElement>(ParamContent));

                    TextBlock SearchIco = new ()
                    {
                        Text = "\ue6a2",
                        FontSize = 17,
                        Foreground = "MistyFern".FindSolidBrush(),
                        FontFamily = "Icon".FindSource<FontFamily>(),
                        HorizontalAlignment = HorizontalAlignment.Center,
                        VerticalAlignment = VerticalAlignment.Center,
                    };

                    Border Search = new()
                    {
                        Height = 35,
                        Width = 35,
                        Name = _map.Key,
                        Margin = new Thickness(3),
                        CornerRadius = new CornerRadius(7),
                        Background = "JadeFlow".FindSolidBrush(),
                        VerticalAlignment = VerticalAlignment.Center,
                        HorizontalAlignment = HorizontalAlignment.Center,
                        Child = SearchIco
                    };
                    
                    Search.PreviewMouseUp += messageBox.ButtonSearchStart;
                    messageBox.SubcripBorderManager.Add(_map.Key, new WeakReference<Border>(Search));
                    mainContentGrid.SetGridWidget(_irow, 0, ParamName);
                    mainContentGrid.SetGridWidget(_irow, 1, ParamContent);
                    mainContentGrid.SetGridWidget(_irow, 2, Search);

                    _irow++;
                }

                ListBox FilterComboBox = new()
                {
                    MinHeight = 130,
                    Height = 175,
                    Style = "ListBoxItem".FindSource<Style>(),
                    Margin = new Thickness(12, 4, 12, 4),
                    VerticalAlignment = VerticalAlignment.Center,
                    VerticalContentAlignment = VerticalAlignment.Center,
                    HorizontalContentAlignment = HorizontalAlignment.Center,
                    HorizontalAlignment = HorizontalAlignment.Stretch
                };

                FilterComboBox.SelectionChanged += SelectionChange;
                messageBox.ListBoxWeak = new WeakReference<ListBox>(FilterComboBox);

                int column = 0;
                Grid bottonGrid = new()
                {
                    MinHeight = 30.0,
                    HorizontalAlignment = HorizontalAlignment.Stretch,
                    VerticalAlignment = VerticalAlignment.Stretch,
                    Margin = new Thickness(5, 5, 5, 5)
                };
                foreach (var button in options)
                {
                    bottonGrid.ColumnDefinitions.Add(new ColumnDefinition() { Width = new GridLength(1, GridUnitType.Star) });
                    VariantButton variant = new VariantButton()
                    {
                        Content = button,
                        FontFamily = "YaHei".FindSource<FontFamily>(),
                        FontSize = 11.0,
                        Foreground = "DeepMatrix".FindSolidBrush(),
                        Margin = new Thickness(5, 0, 5, 0),
                        MinWidth = 100.0,
                        MinHeight = 25
                    };
                    bottonGrid.SetGridWidget(0, column, variant);
                    messageBox.SubcripElementManager.Add(button, new WeakReference<FrameworkElement>(variant));
                    variant.PreviewMouseUp += messageBox.ButtonClick;
                    column++;

                }
                mainGrid.SetGridWidget(0, 0, TitleGrid);
                mainGrid.SetGridWidget(1, 0, mainContentGrid);
                mainGrid.SetGridWidget(2, 0, FilterComboBox);
                mainGrid.SetGridWidget(3, 0, bottonGrid);

                messageBox.AddChild(mainGrid);
                messageBox.ShowDialog();
                messageBox.DisposeSubcription();

            });

            messageBox?.GetUnautoArgcontent();
            return (InvokeOut.index, messageBox?.SearchResultMap);
        }

        private void ButtonClick(object sender, MouseButtonEventArgs e)
        {
            if (sender is VariantButton variant) 
            {
                int index = 0;
                InvokeOut.content = variant.Content.GetSafetyChar();
                foreach(var i in SubcripElementManager)
                {
                    if (i.Value.TryGetTarget(out FrameworkElement? _Framework) && _Framework is not null and Button _Button)
                    {
                        if (i.Key == InvokeOut.content)
                        {
                            InvokeOut.index = index;
                            break;
                        }
                        index++;
                    }
                }
                OptionOut.index = InvokeOut.index;
            }
            Close();
        }

        private void ButtonSearchStart(object sender, MouseButtonEventArgs e)
        {
            if (sender is Border search && search.FindVisualUpObject<Grid>() is not null and Grid contentGrid)
            {
                TextBox? _TextBox = contentGrid.GetGridRowWidget<TextBox>(Grid.GetRow(search), search.Name);
                if (_TextBox is not null)
                {
                    MatchDeviceInfos(_TextBox.Text, _TextBox.Name);
                }
            }
        }

        private void DisposeSubcription()
        {
            foreach (var pair in SubcripElementManager)
            {
                if (pair.Value.TryGetTarget(out FrameworkElement? _Frame))
                {
                    if (_Frame is Button _Button)
                    {
                        _Button.PreviewMouseUp -= ButtonClick;
                    }

                    else if (_Frame is ListBox _ListBox)
                    {
                        _ListBox.SelectionChanged -= SelectionChange;
                    }
                }
            }

            foreach (var pair in SubcripBorderManager)
            {
                if (pair.Value.TryGetTarget(out Border? _Frame))
                {
                    if (_Frame is Border _Border)
                    {
                        _Border.PreviewMouseUp -= ButtonSearchStart;
                    }
                }
            }
            SubcripBorderManager.Clear();
        }

        public async void MatchDeviceInfos(string content = "", string flag = "IMEI")
        {
            void Add(string key, List<string> value)
            {
                if (SearchMatchMap.ContainsKey(key))
                {
                    SearchMatchMap[key] = value;
                }
                else
                {
                    SearchMatchMap.Add(key, value);
                }
            }

            object? result = await ActivityDetetorServer.AutoFindDim(content, flag);

            if (result is not null and Supabase.Postgrest.Responses.ModeledResponse<WorkOrderUnfold> unfoldResponse && unfoldResponse.Models.Count > 0)
            {
                if (unfoldResponse.Models.Count > 0)
                {
                    await Application.Current.Dispatcher.InvokeAsync(() =>
                    {
                        List<string> IMEIS = [.. unfoldResponse.Models.Select(x => x.Imei)];
                        List<string> SNS = [.. unfoldResponse.Models.Select(x => x.Sn)];
                        List<string> BLUES = [.. unfoldResponse.Models.Select(x => x.BlueMac)];
                        List<string> DOIDS = [.. unfoldResponse.Models.Select(x => x.Id)];

                        IEnumerable<string> ItemsSources = [];
                        switch (flag)
                        {
                            case "IMEI":
                                ItemsSources = IMEIS;
                                break;
                            case "SN":
                                ItemsSources = SNS;
                                break;
                            case "BLUE":
                                ItemsSources = BLUES;
                                break;
                            case "DOID":
                                ItemsSources = DOIDS;
                                break;
                        }

                        Add("IMEI", IMEIS);
                        Add("SN", SNS);
                        Add("BLUE", BLUES);
                        Add("DOID", DOIDS);

                        if (ListBoxWeak?.TryGetTarget(out ListBox? _ListBox) is not null and bool statee && _ListBox is not null)
                        {
                            _ListBox.ItemsSource = ItemsSources;
                        }
                    });
                }
                else
                {
                    if (ListBoxWeak?.TryGetTarget(out ListBox? _ListBox) is not null and bool statee && _ListBox is not null)
                    {
                        IEnumerable<string> Empty = [];
                        _ListBox.ItemsSource = Empty;
                    }
                }
            }

            else
            {
                await Application.Current.Dispatcher.InvokeAsync(() =>
                {
                    if (result is not null and Dictionary<string, List<object>> tableDataMap)
                    {
                        IEnumerable<string> ExpectDatas = [];

                        if (tableDataMap.TryGetValue("sn", out List<object>? _SNS) &&
                                            tableDataMap.TryGetValue("imei", out List<object>? _IMEIS) &&
                                            tableDataMap.TryGetValue("blue_mac", out List<object>? _MACS) &&
                                            tableDataMap.TryGetValue("id", out List<object>? _IDS))
                        {

                            List<string> IMEIS = [.. _IMEIS.Select(x => x.GetSafetyChar())];
                            List<string> SNS = [.. _SNS.Select(x => x.GetSafetyChar())];
                            List<string> MACS = [.. _MACS.Select(x => x.GetSafetyChar())];
                            List<string> IDS = [.. _IDS.Select(x => x.GetSafetyChar())];

                            Add("IMEI", IMEIS);
                            Add("SN", SNS);
                            Add("BLUE", MACS);
                            Add("DOID", IDS);

                            switch (flag)
                            {
                                case "IMEI":
                                    ExpectDatas = IMEIS;
                                    break;
                                case "SN":
                                    ExpectDatas = SNS;
                                    break;
                                case "BLUE":
                                    ExpectDatas = MACS;
                                    break;
                                case "DOID":
                                    ExpectDatas = IDS;
                                    break;
                            }
                        }

                        if (ListBoxWeak?.TryGetTarget(out ListBox? _ListBox) is not null and bool statee && _ListBox is not null)
                        {
                            _ListBox.ItemsSource = ExpectDatas;
                        }
                    }

                    else
                    {
                        if (ListBoxWeak?.TryGetTarget(out ListBox? _ListBox) is not null and bool statee && _ListBox is not null)
                        {
                            IEnumerable<string> Empty = [];
                            _ListBox.ItemsSource = Empty;
                        }
                    }
                });
            }
        }

        public void GetUnautoArgcontent()
        {
            foreach (var _pair in SubcripElementManager) //遍历所有文本框
            {
                if (_pair.Value.TryGetTarget(out FrameworkElement? _Framework) &&
                    _Framework is not null and TextBox _TextBox)
                {
                    if (SearchResultMap.ContainsKey(_TextBox.Name))
                    {
                        SearchResultMap[_TextBox.Name] = _TextBox.Text;
                    }
                    else
                    {
                        SearchResultMap.TryAdd(_TextBox.Name, _TextBox.Text);
                    }
                }
            }
            SubcripElementManager.Clear();
        }

        public static void SelectionChange(object sender, SelectionChangedEventArgs e)
        {
            if (sender is ListBox _ListBox && 
                _ListBox.FindVisualUpObject<CustomMessageBox>() is not null and CustomMessageBox self)
            {
                int index = _ListBox.SelectedIndex;
                List<Grid> Grids = [.. _ListBox.FindVisualUpObjects<Grid, Grid>().Where(x => x.Name == "ContentLayout")]; //查找主布局
                if (Grids.Count == 1)
                {
                    foreach(var _TextBox in Grids[0].FindVisualUpObjects<Grid, TextBox>()) //遍历所有文本框
                    {
                        if (self.SearchMatchMap.TryGetValue(_TextBox.Name, out List<string>? duty)) // 获取结果集合
                        {
                            if (index >= 0 && index < duty.Count)
                            {
                                string Content = duty[index];
                                _TextBox.Text = Content;
                            }
                        }
                    }
                }
            }
        }
    }

    public class VariantButton : Button
    {
        
        public VariantButton()
        {
            if (new FontFamilyConverter().ConvertFrom("Microsoft YaHei") is not null and FontFamily family)
            {
                FontFamily = family;
            }
        }

        public CornerRadius CornerRadius
        {
            set { SetValue(CornerRadiusProperty, value); }
            get { return (CornerRadius)GetValue(CornerRadiusProperty); }
        }

        public Brush NormalBdColor
        {
            set { SetValue(NormalBdColorProperty, value); }
            get { return (Brush)GetValue(NormalBdColorProperty); }
        }

        public Brush NormalBgColor
        {
            set { SetValue(NormalBgColorProperty, value); }
            get { return (Brush)GetValue(NormalBgColorProperty); }
        }
        
        public Brush MouseHoverBgColor
        {
            get { return (Brush)GetValue(MouseHoverBgColorProperty); }
            set { SetValue(MouseHoverBgColorProperty, value); }
        }
        
        public Brush MousePreeBgColor
        {
            get { return (Brush)GetValue(MousePreeBgColorProperty); }
            set { SetValue(MousePreeBgColorProperty, value); }
        }
        
        public Brush MouseHoverBdColor
        {
            get { return (Brush)GetValue(MouseHoverBdColorProperty); }
            set { SetValue(MouseHoverBdColorProperty, value); }
        }
        
        public Brush MousePreeBdColor
        {
            get { return (Brush)GetValue(MousePreeBdColorProperty); }
            set { SetValue(MousePreeBdColorProperty, value); }
        }

        public Brush ForegroundColor
        {
            get { return (Brush)GetValue(ForegroundColorProperty); }
            set { SetValue(ForegroundColorProperty, value); }
        }


        public static readonly DependencyProperty CornerRadiusProperty =
            DependencyProperty.Register(nameof(CornerRadius), typeof(CornerRadius), typeof(VariantButton), new PropertyMetadata(new CornerRadius(3)));

        public static readonly DependencyProperty MouseHoverBdColorProperty =
            DependencyProperty.Register(nameof(MouseHoverBdColor), typeof(Brush), typeof(VariantButton), new PropertyMetadata("DeepMatrix".FindSolidBrush()));

        public static readonly DependencyProperty MouseHoverBgColorProperty =
            DependencyProperty.Register(nameof(MouseHoverBgColor), typeof(Brush), typeof(VariantButton), new PropertyMetadata("MoonlitLavender".FindSolidBrush()));

        public static readonly DependencyProperty MousePreeBdColorProperty =
            DependencyProperty.Register(nameof(MousePreeBdColor), typeof(Brush), typeof(VariantButton), new PropertyMetadata("BurgundyNight".FindSolidBrush()));

        public static readonly DependencyProperty MousePreeBgColorProperty =
            DependencyProperty.Register(nameof(MousePreeBgColor), typeof(Brush), typeof(VariantButton), new PropertyMetadata("ArcticMist".FindSolidBrush()));

        public static readonly DependencyProperty NormalBdColorProperty =
            DependencyProperty.Register(nameof(NormalBdColor), typeof(Brush), typeof(VariantButton), new PropertyMetadata("StormyHarbor".FindSolidBrush()));

        public static readonly DependencyProperty NormalBgColorProperty =
            DependencyProperty.Register(nameof(NormalBgColor), typeof(Brush), typeof(VariantButton), new PropertyMetadata("MoonlitLavender".FindSolidBrush()));

        public static readonly DependencyProperty ForegroundColorProperty =
            DependencyProperty.Register(nameof(ForegroundColor), typeof(Brush), typeof(VariantButton), new PropertyMetadata("OverBlack".FindSolidBrush()));
    }

    public class EnjoyRichTextBox : RichTextBox
    {
        public readonly Queue<string> InputQueue = new Queue<string>();

        int CacheLength = 200;

        public class HighLightInfoBase
        {
            public Brush? Background = null;
            public Brush? Foreground = null;
            public FontFamily? Family = null;
            public double? FontSize = null;

            public HighLightInfoBase(string? _background = null,
                                     string? _foreground = null,
                                     FontFamily? _family = null,
                                     double? _fontsize = null)
            {
                var convert = new BrushConverter();
                if (_background != null)
                {
                    object? back = convert.ConvertFrom(_background);
                    if (back != null) Background = (Brush)back;
                }
                if (_foreground != null)
                {
                    object? fore = convert.ConvertFrom(_foreground);
                    if (fore != null) Foreground = (Brush)fore;
                }
                Family = _family;
                FontSize = _fontsize;
                
            }
        }

        public sealed class HighLightInfoGroup : HighLightInfoBase
        {
            public bool isRegexp = true;
            public string Content;

            public HighLightInfoGroup(string _content, 
                                      bool _isRegexp, 
                                      string? _background = null, 
                                      string? _foreground = null, 
                                      FontFamily? _family = null, 
                                      double? _fontsize = null) : 
                base(_background, _foreground, _family, _fontsize)
            {
                Content = _content;
                isRegexp = _isRegexp;
            }
        }

        public EnjoyRichTextBox()
        {
            this.Document ??= new FlowDocument();
            this.Document.LineHeight = 1;
        }

        public static readonly ILogger Logger = Log.ForContext<EnjoyRichTextBox>();

        private static readonly DependencyProperty CornerRadiusProperty = DependencyProperty.Register(
            nameof(CornerRadius),
            typeof(CornerRadius),
            typeof(EnjoyRichTextBox));

        private static readonly DependencyProperty AppendTextProperty = DependencyProperty.Register(
            nameof(AppendLineText),
            typeof(ObservableCollection<string>),
            typeof(EnjoyRichTextBox),
            new PropertyMetadata(null, AppendTextCollectionChangeCallBack));

        private static readonly DependencyProperty HighLightDetailProperty = DependencyProperty.Register(
            nameof(DetailHighLightCollection),
            typeof(ObservableCollection<HighLightInfoGroup>),
            typeof(EnjoyRichTextBox),
            new PropertyMetadata(new ObservableCollection<HighLightInfoGroup>()));

        private static readonly DependencyProperty HighLightFocusedProperty = DependencyProperty.Register(
            nameof(FocusedHighLightParagraphAttribute),
            typeof(HighLightInfoBase),
            typeof(EnjoyRichTextBox),
            new PropertyMetadata(null));

        private static readonly DependencyProperty HighLightGlobalProperty = DependencyProperty.Register(
            nameof(GlobalHighLightParagraphAttribute),
            typeof(HighLightInfoBase),
            typeof(EnjoyRichTextBox),
            new PropertyMetadata(null));

        private static readonly DependencyProperty DocuContentCaptrueProperty = DependencyProperty.Register(
            nameof(DocuContentCaptrue),
            typeof(bool),
            typeof(EnjoyRichTextBox),
            new PropertyMetadata(false, DocuContentCaptrueChangeCallBack));

        private static readonly DependencyProperty DocuContentPushProperty = DependencyProperty.Register(
            nameof(DocuContentPushCommand),
            typeof(ICommand),
            typeof(EnjoyRichTextBox),
            new PropertyMetadata(null));

        public bool DocuContentCaptrue
        {
            get => (bool)GetValue(DocuContentCaptrueProperty);
            set => SetValue(DocuContentCaptrueProperty, value);
        }

        public ICommand DocuContentPushCommand
        {
            get => (ICommand)GetValue(DocuContentPushProperty);
            set => SetValue(DocuContentPushProperty, value);
        }

        public CornerRadius CornerRadius
        {
            set
            {
                SetValue(CornerRadiusProperty, value);
            }
            get
            {
                return (CornerRadius)GetValue(CornerRadiusProperty);
            }
        }

        public ObservableCollection<string> AppendLineText
        {
            set
            {
                SetValue(AppendTextProperty, value);
            }
            get
            {
                return (ObservableCollection<string>)GetValue(AppendTextProperty);
            }
        }

        public ObservableCollection<HighLightInfoGroup> DetailHighLightCollection
        {
            set
            {
                SetValue(HighLightDetailProperty, value);
            }
            get
            {
                return (ObservableCollection<HighLightInfoGroup>)GetValue(HighLightDetailProperty);
            }
        }

        public HighLightInfoBase FocusedHighLightParagraphAttribute
        {
            set
            {
                SetValue(HighLightFocusedProperty, value);
            }
            get
            {
                return (HighLightInfoBase)GetValue(HighLightFocusedProperty);
            }
        }

        public HighLightInfoBase GlobalHighLightParagraphAttribute
        {
            set
            {
                SetValue(HighLightGlobalProperty, value);
            }
            get
            {
                return (HighLightInfoBase)GetValue(HighLightGlobalProperty);
            }
        }

        private static void DocuContentCaptrueChangeCallBack(DependencyObject sender, DependencyPropertyChangedEventArgs e)
        {
            if (sender is not null and EnjoyRichTextBox self)
            {
                TextPointer start = self.Document.ContentStart;
                TextPointer end = self.Document.ContentEnd;
                TextRange getRange = new(start, end);
                string DocuContent = getRange.Text;
                Logger.DebudElite("---", DocuContent);
                self.DocuContentPushCommand?.Execute(DocuContent);
            }
        }

        public static void AppendTextCollectionChangeCallBack(DependencyObject sender, DependencyPropertyChangedEventArgs e)
        {
            if (sender is not null and EnjoyRichTextBox self)
            {
                if (e.OldValue is ObservableCollection<string> oldCollection)
                {
                    WeakEventManager<ObservableCollection<string>, NotifyCollectionChangedEventArgs>
                        .RemoveHandler(oldCollection, nameof(ObservableCollection<string>.CollectionChanged), self.CollectionContentChange);
                }


                if (e.NewValue is ObservableCollection<string> newCollection)
                {
                    WeakEventManager<ObservableCollection<string>, NotifyCollectionChangedEventArgs>
                        .AddHandler(newCollection, nameof(ObservableCollection<string>.CollectionChanged), self.CollectionContentChange);
                }
            }
        }

        public void CollectionContentChange(object? sender, NotifyCollectionChangedEventArgs e)
        {
            if (e.Action == NotifyCollectionChangedAction.Add && e.NewItems is not null)
            {

                foreach (var text in e.NewItems)
                {
                    if (text is string validText)
                    {
                        AppendParaGragh(validText);
                    }
                }

                Dispatcher.BeginInvoke(() =>
                {
                    if (sender is ObservableCollection<string> Collection && Collection.Count > CacheLength)
                    {
                        for (int index = 0; index < CacheLength; index++) Collection.RemoveAt(0);
                    }
                });
            }
        }

        public (Paragraph, bool) MatchForHighLight(string content)
        {
            Paragraph paragraph = new();
            bool isValid = false;
            if (DetailHighLightCollection.Count > 0)
            {
                int start = 0;
                foreach (HighLightInfoGroup HiL in DetailHighLightCollection)
                {
                    if (HiL.isRegexp)
                    {
                        int matchIndex = 0;
                        MatchCollection matchAll = Regex.Matches(content, HiL.Content);
                        foreach (Match match in matchAll)
                        {
                            matchIndex++;
                            if (start < match.Index)
                            {
                                paragraph.Inlines.Add(new Run(content[start..match.Index]));
                                start = match.Index + match.Length;
                            }

                            Run matchRun = new(content.Substring(match.Index, match.Length));

                            if (HiL.Foreground != null) Foreground = HiL.Foreground;
                            if (HiL.Background != null) Background = HiL.Background;
                            if (HiL.Family != null) FontFamily = HiL.Family;
                            if (HiL.FontSize != null) FontSize = (double)HiL.FontSize;

                            paragraph.Inlines.Add(matchRun);
                            if (matchIndex == matchAll.Count)
                            {
                                Run lastRun = new(content[(match.Index + match.Length)..content.Length]);
                                paragraph.Inlines.Add(lastRun);
                            }
                        }
                        if (matchIndex != 0) isValid = true;
                    }
                    else
                    {
                        int matchIndex = 0;
                        while (true)
                        {
                            int index = content.IndexOf(HiL.Content, start);
                            int size = HiL.Content.Length;
                            if (index == -1)
                            {
                                Run lastRun = new(content[start..content.Length]);
                                paragraph.Inlines.Add(lastRun);
                                break;
                            }
                            else
                            {
                                matchIndex++;
                                if (start < index)
                                {
                                    paragraph.Inlines.Add(new Run(content[start..index]));
                                    start = index + size;
                                }

                                Run matchRun = new(content.Substring(index, size));

                                if (HiL.Foreground != null) Foreground = HiL.Foreground;
                                if (HiL.Background != null) Background = HiL.Background;
                                if (HiL.Family != null) FontFamily = HiL.Family;
                                if (HiL.FontSize != null) FontSize = (double)HiL.FontSize;
                                paragraph.Inlines.Add(matchRun);
                            }
                        }
                        if (matchIndex != 0) isValid = true;
                    }
                }
            }
            else
            {
                paragraph.Inlines.Add(new Run(content));
                return (paragraph, false);
            }
            if (isValid)
            {
                return (paragraph, true);
            }
            else
            {
                paragraph.Inlines.Add(new Run(content));
                return (paragraph, false);
            }
        }

        private void AppendParaGragh(string text)
        {

            Dispatcher.Invoke(() =>
            {
                if (this.Document != null)
                {
                    (Paragraph, bool) paragraph = MatchForHighLight(text);
                    if (paragraph.Item2)
                    {
                        if (FocusedHighLightParagraphAttribute != null)
                        {
                            if (FocusedHighLightParagraphAttribute.Background != null) paragraph.Item1.Background = FocusedHighLightParagraphAttribute.Background;
                            if (FocusedHighLightParagraphAttribute.Foreground != null) paragraph.Item1.Foreground = FocusedHighLightParagraphAttribute.Foreground;
                            if (FocusedHighLightParagraphAttribute.FontSize != null) paragraph.Item1.FontSize = (double)FocusedHighLightParagraphAttribute.FontSize;
                            if (FocusedHighLightParagraphAttribute.Family != null) paragraph.Item1.FontFamily = FocusedHighLightParagraphAttribute.Family;
                        }
                    }
                    else
                    {
                        if (GlobalHighLightParagraphAttribute != null)
                        {
                            if (GlobalHighLightParagraphAttribute.Background != null) paragraph.Item1.Background = GlobalHighLightParagraphAttribute.Background;
                            if (GlobalHighLightParagraphAttribute.Foreground != null) paragraph.Item1.Foreground = GlobalHighLightParagraphAttribute.Foreground;
                            if (GlobalHighLightParagraphAttribute.FontSize != null) paragraph.Item1.FontSize = (double)GlobalHighLightParagraphAttribute.FontSize;
                            if (GlobalHighLightParagraphAttribute.Family != null) paragraph.Item1.FontFamily = GlobalHighLightParagraphAttribute.Family;
                        }
                    }

                    Paragraph rowContent = paragraph.Item1;
                    rowContent.LineHeight = FontSize + 0.6;
                    rowContent.LineStackingStrategy = LineStackingStrategy.BlockLineHeight;
                    Document.Blocks.Add(rowContent);
                    ScrollToEnd();
                }
            });
        }

        public void AppendToEnd(string text)
        {
            if (this.Document != null)
            {
                Dispatcher.Invoke(() =>
                {
                    TextPointer end = this.Document.ContentEnd;
                    end.InsertTextInRun(text);
                    ScrollToEnd();
                });
            }
        }

    }

    public class EnjoyListBox : ListBox
    {

        public EnjoyListBox()
        {
            this.PreviewMouseDown += ItemClick;
            this.SelectionChanged += SelectedChange;
            this.GotFocus += ItemGotFocus;
            this.LostFocus += ItemLoseFocus;
        }

        public ICommand SelectItemsChangeCommand
        {
            get => (ICommand)GetValue(ItemsChangeCommandProperty);
            set => SetValue(ItemsChangeCommandProperty, value);
        }

        public ICommand ItemEditInfoCommand
        {
            get => (ICommand)GetValue(ItemEditInfoCommandProperty);
            set => SetValue(ItemEditInfoCommandProperty, value);
        }

        public readonly ILogger Logger = Log.ForContext<EnjoyListBox>();

        public static void SelectedChange(object d, SelectionChangedEventArgs e)
        {
            EnjoyListBox self = (EnjoyListBox)d;
            self.SelectItemsChangeCommand.Execute(self.SelectedItems.Cast<CommandStruct>().ToList());
        }

        private static readonly DependencyProperty ItemsChangeCommandProperty = DependencyProperty.Register(
            nameof(SelectItemsChangeCommand),
            typeof(ICommand),
            typeof(EnjoyListBox),
            new PropertyMetadata(null));

        private static readonly DependencyProperty ItemEditInfoCommandProperty = DependencyProperty.Register(
            nameof(ItemEditInfoCommand),
            typeof(ICommand),
            typeof(EnjoyListBox),
            new PropertyMetadata(null));

        private static readonly DependencyProperty ItemCornerRadiusProperty = DependencyProperty.Register(
            nameof(ItemCornerRadius),
            typeof(CornerRadius),
            typeof(EnjoyListBox));

        private static readonly DependencyProperty ItemheightProperty = DependencyProperty.Register(
            nameof(Itemheight),
            typeof(double),
            typeof(EnjoyListBox));

        private static readonly DependencyProperty ItemFontSizeProperty = DependencyProperty.Register(
            nameof(ItemFontSize),
            typeof(double),
            typeof(EnjoyListBox));

        private static readonly DependencyProperty ScrollToViewProperty = DependencyProperty.Register(
            nameof(ScrollToView),
            typeof(CommandSectionModel.CommandStruct),
            typeof(EnjoyListBox),
            new PropertyMetadata(null, ScrollToViewChange));

        public CornerRadius ItemCornerRadius
        {
            set
            {
                SetValue(ItemCornerRadiusProperty, value);
            }
            get
            {
                return (CornerRadius)GetValue(ItemCornerRadiusProperty);
            }
        }

        public double Itemheight
        {
            set
            {
                SetValue(ItemheightProperty, value);
            }
            get
            {
                return (double)GetValue(ItemheightProperty);
            }
        }

        public double ItemFontSize
        {
            set
            {
                SetValue(FontSizeProperty, value);
            }
            get
            {
                return (double)GetValue(FontSizeProperty);
            }
        }

        public CommandSectionModel.CommandStruct ScrollToView
        {
            set
            {
                SetValue(ScrollToViewProperty, value);
            }
            get
            {
                return (CommandSectionModel.CommandStruct)GetValue(ScrollToViewProperty);
            }
        }

        public static void ItemClick(object sender, MouseButtonEventArgs e)
        {
            EnjoyListBox self = (EnjoyListBox)sender;
            DependencyObject MouseUpDependencyObject = (DependencyObject)e.OriginalSource;
            ListBoxItem? CurrentSelectedItem = MouseUpDependencyObject.FindVisualUpObject<ListBoxItem>();
            if (CurrentSelectedItem is not null)
            {
                if (CurrentSelectedItem.IsSelected)
                {
                    CurrentSelectedItem.IsSelected = false;
                }
                else
                {
                    CurrentSelectedItem.IsSelected = true;
                }
            }
        }

        public static void ItemGotFocus(object sender, RoutedEventArgs e)
        {
            EnjoyListBox self = (EnjoyListBox)sender;
            DependencyObject GotFocusDependencyObject = (DependencyObject)e.OriginalSource;
            ListBoxItem? CurrentSelectedItem = GotFocusDependencyObject.FindVisualUpObject<ListBoxItem>();
            List<TextBlock> FindTextBlocks = GotFocusDependencyObject.FindVisualUpObjects<ListBoxItem, TextBlock>();
            foreach (var textBlock in FindTextBlocks)
            {
                textBlock.Visibility = Visibility.Visible;
                if (CurrentSelectedItem is not null && CurrentSelectedItem.Content is CommandStruct commandData)
                {
                    int index = self.ItemContainerGenerator.IndexFromContainer(CurrentSelectedItem);
                    textBlock.MouseDown += (d, e) => self.EditItemInfoSend(commandData, index, d, e);
                }
            }
        }

        public static void ItemLoseFocus(object sender, RoutedEventArgs e)
        {
            EnjoyListBox self = (EnjoyListBox)sender;
            DependencyObject GotFocusDependencyObject = (DependencyObject)e.OriginalSource;
            ListBoxItem? CurrentSelectedItem = GotFocusDependencyObject.FindVisualUpObject<ListBoxItem>();
            List<TextBlock> FindTextBlocks = GotFocusDependencyObject.FindVisualUpObjects<ListBoxItem, TextBlock>();
            foreach (var textBlock in FindTextBlocks)
            {
                textBlock.Visibility = Visibility.Collapsed;
                if (CurrentSelectedItem is not null && CurrentSelectedItem.Content is CommandStruct commandData)
                {
                    int index = self.ItemContainerGenerator.IndexFromContainer(CurrentSelectedItem);
                    textBlock.MouseDown -= (d, e) => self.EditItemInfoSend(commandData, index, d, e);
                }
            }
        }

        public void EditItemInfoSend(CommandStruct command, int index, object sender, MouseButtonEventArgs e)
        {
            ItemEditInfoCommand.Execute(new AlterCommandStruct(command, index));
        }

        public static void ScrollToViewChange(DependencyObject d, DependencyPropertyChangedEventArgs e)
        {
            EnjoyListBox self = (EnjoyListBox)d;
            if (e.NewValue is CommandSectionModel.CommandStruct _obj)
            {
                self.Dispatcher.BeginInvoke(new Action(() =>
                {
                    self.ScrollIntoView(_obj);
                    self.SelectedItem = _obj;
                    int indexof = self.Items.IndexOf(_obj);
                    if (indexof != -1) 
                    {
                        self.ItemEditInfoCommand.Execute(new AlterCommandStruct(_obj, indexof)); 
                    }
                }));
            }
            else
            {
                self.Logger.Debug($"{e.NewValue} analysis fail");
            }
        }

    }
                    
    public class ActivityListBox : ListBox
    {
        private readonly ILogger Logger = Log.ForContext<ActivityListBox>();

        private static readonly DependencyProperty ItemCornerRadiusProperty = DependencyProperty.Register(
            nameof(ItemCornerRadius),
            typeof(CornerRadius),
            typeof(ActivityListBox)
            );

        private static readonly DependencyProperty ItemheightProperty = DependencyProperty.Register(
            nameof(Itemheight),
            typeof(double),
            typeof(ActivityListBox)
            );

        private static readonly DependencyProperty ItemFontSizeProperty = DependencyProperty.Register(
            nameof(ItemFontSize),
            typeof(double),
            typeof(ActivityListBox)
            );

        private static readonly DependencyProperty ScrollToViewProperty = DependencyProperty.Register(
            nameof(ScrollToView),
            typeof(ActivitySectionModel.ActivityListBoxItemStruct),
            typeof(ActivityListBox),
            new PropertyMetadata(null, ScrollToViewChange)
            );

        public CornerRadius ItemCornerRadius
        {
            set
            {
                SetValue(ItemCornerRadiusProperty, value);
            }
            get
            {
                return (CornerRadius)GetValue(ItemCornerRadiusProperty);
            }
        }

        public double Itemheight
        {
            set
            {
                SetValue(ItemheightProperty, value);
            }
            get
            {
                return (double)GetValue(ItemheightProperty);
            }
        }

        public double ItemFontSize
        {
            set
            {
                SetValue(FontSizeProperty, value);
            }
            get
            {
                return (double)GetValue(FontSizeProperty);
            }
        }

        public ActivitySectionModel.ActivityListBoxItemStruct ScrollToView
        {
            set
            {
                SetValue(ScrollToViewProperty, value);
            }
            get
            {
                return (ActivitySectionModel.ActivityListBoxItemStruct)GetValue(ScrollToViewProperty);
            }
        }

        public static void ScrollToViewChange(DependencyObject d, DependencyPropertyChangedEventArgs e)
        {
            ActivityListBox self = (ActivityListBox)d;
            if (e.NewValue is ActivitySectionModel.ActivityListBoxItemStruct _obj)
            {
                self.Dispatcher.BeginInvoke(new Action(() =>
                {
                    self.ScrollIntoView(_obj);
                    self.SelectedItem = _obj;
                }));
            }
            else
            {
                self.Logger.Debug($"{e.NewValue} analysis fail");
            }
        }

    }

    public class EnjoySelector : ToggleButton
    {
        private static readonly ILogger Logger = Log.ForContext<EnjoySelector>();
        private static readonly ConditionalWeakTable<Control, ConnectFlag> SubscriptionKeyvaluePair = [];
        private List<string> SelectedValueJoin = [];
        public EnjoySelector()
        {
            FontFamily = "YaHei".FindSource<FontFamily>() ?? new FontFamily("KaiTi");
            UseLayoutRounding = true;
            WeakEventManager<ToggleButton, MouseButtonEventArgs>.AddHandler(this, nameof(ToggleButton.PreviewMouseUp), PreViewMouseUpEvent);
        }

        public override void OnApplyTemplate()
        {
            Window window = Window.GetWindow(this);
            window.Deactivated += WindowDeactiveEventTrigger;
            window.Closed += WindowClosedEventTrigger;
        }

        public CornerRadius CornerRadius
        {
            set { SetValue(CornerRadiusProperty, value); }
            get { return (CornerRadius)GetValue(CornerRadiusProperty); }
        }

        public Brush NormalBdColor
        {
            set { SetValue(NormalBdColorProperty, value); }
            get { return (Brush)GetValue(NormalBdColorProperty); }
        }

        public Brush NormalBgColor
        {
            set { SetValue(NormalBgColorProperty, value); }
            get { return (Brush)GetValue(NormalBgColorProperty); }
        }

        public Brush MouseHoverBgColor
        {
            get { return (Brush)GetValue(MouseHoverBgColorProperty); }
            set { SetValue(MouseHoverBgColorProperty, value); }
        }

        public Brush MousePreeBgColor
        {
            get { return (Brush)GetValue(MousePreeBgColorProperty); }
            set { SetValue(MousePreeBgColorProperty, value); }
        }

        public Brush MouseHoverBdColor
        {
            get { return (Brush)GetValue(MouseHoverBdColorProperty); }
            set { SetValue(MouseHoverBdColorProperty, value); }
        }

        public Brush MousePreeBdColor
        {
            get { return (Brush)GetValue(MousePreeBdColorProperty); }
            set { SetValue(MousePreeBdColorProperty, value); }
        }

        public ObservableCollection<string> SelectedValue
        {
            set
            {
                SetValue(SelectedValueProperty, value);
            }
            get
            {
                return (ObservableCollection<string>)GetValue(SelectedValueProperty);
            }
        }

        public CornerRadius SleCornerRadius
        {
            set
            {
                SetValue(SleCornerRadiusProperty, value);
            }
            get
            {
                return (CornerRadius)GetValue(SleCornerRadiusProperty);
            }
        }

        public bool ContentChangeSwitch
        {
            set
            {
                SetValue(ContentChangeSwitchProperty, value);
            }
            get
            {
                return (bool)GetValue(ContentChangeSwitchProperty);
            }
        }

        public double Sleheight
        {
            set
            {
                SetValue(SleheightProperty, value);
            }
            get
            {
                return (double)GetValue(SleheightProperty);
            }
        }

        public double SleFontSize
        {
            set
            {
                SetValue(SleFontSizeProperty, value);
            }
            get
            {
                return (double)GetValue(SleFontSizeProperty);
            }
        }

        public double SleIconFontSize
        {
            set
            {
                SetValue(SleIconFontSizeProperty, value);
            }
            get
            {
                return (double)GetValue(SleIconFontSizeProperty);
            }
        }

        public IEnumerable ItemsSource
        {
            set
            {
                SetValue(ItemsSourceProperty, value);
            }
            get
            {
                return (IEnumerable)GetValue(ItemsSourceProperty);
            }
        }

        public IEnumerable ApplyItemsSource
        {
            set
            {
                SetValue(ApplyItemsSourceProperty, value);
            }
            get
            {
                return (IEnumerable)GetValue(ApplyItemsSourceProperty);
            }
        }

        public Dictionary<SelectorContentStruct, ObservableCollection<SelectorContentStruct>> ItemsSourcePair
        {
            set
            {
                SetValue(ItemsSourcePairProperty, value);
            }
            get
            {
                return (Dictionary<SelectorContentStruct, ObservableCollection<SelectorContentStruct>>)GetValue(ItemsSourcePairProperty);
            }
        }

        public Brush ForegroundColor
        {
            get { return (Brush)GetValue(ForegroundColorProperty); }
            set { SetValue(ForegroundColorProperty, value); }
        }

        public static readonly DependencyProperty CornerRadiusProperty =
            DependencyProperty.Register(
                nameof(CornerRadius),
                typeof(CornerRadius),
                typeof(EnjoySelector),
                new PropertyMetadata(new CornerRadius(3)));

        public static readonly DependencyProperty MouseHoverBdColorProperty =
            DependencyProperty.Register(
                nameof(MouseHoverBdColor),
                typeof(Brush),
                typeof(EnjoySelector),
                new PropertyMetadata("DeepMatrix".FindSolidBrush()));

        public static readonly DependencyProperty MouseHoverBgColorProperty =
            DependencyProperty.Register(
                nameof(MouseHoverBgColor),
                typeof(Brush),
                typeof(EnjoySelector),
                new PropertyMetadata("MoonlitLavender".FindSolidBrush()));

        public static readonly DependencyProperty MousePreeBdColorProperty =
            DependencyProperty.Register(
                nameof(MousePreeBdColor),
                typeof(Brush),
                typeof(EnjoySelector),
                new PropertyMetadata("BurgundyNight".FindSolidBrush()));

        public static readonly DependencyProperty MousePreeBgColorProperty =
            DependencyProperty.Register(
                nameof(MousePreeBgColor),
                typeof(Brush),
                typeof(EnjoySelector),
                new PropertyMetadata("IvoryGlow".FindSolidBrush()));

        public static readonly DependencyProperty NormalBdColorProperty =
            DependencyProperty.Register(
                nameof(NormalBdColor),
                typeof(Brush),
                typeof(EnjoySelector),
                new PropertyMetadata("StormyHarbor".FindSolidBrush()));

        public static readonly DependencyProperty NormalBgColorProperty =
            DependencyProperty.Register(
                nameof(NormalBgColor),
                typeof(Brush),
                typeof(EnjoySelector),
                new PropertyMetadata("MoonlitLavender".FindSolidBrush()));

        public static readonly DependencyProperty ForegroundColorProperty =
            DependencyProperty.Register(
                nameof(ForegroundColor),
                typeof(Brush),
                typeof(EnjoySelector),
                new PropertyMetadata("OverBlack".FindSolidBrush()));

        private static readonly DependencyProperty SleCornerRadiusProperty =
            DependencyProperty.Register(
                nameof(SleCornerRadius),
                typeof(CornerRadius),
                typeof(EnjoySelector),
                new PropertyMetadata(new CornerRadius(8)));

        private static readonly DependencyProperty SleheightProperty =
            DependencyProperty.Register(
                nameof(Sleheight),
                typeof(double),
                typeof(EnjoySelector),
                new PropertyMetadata(28.0));
        
        private static readonly DependencyProperty ContentChangeSwitchProperty =
            DependencyProperty.Register(
                nameof(ContentChangeSwitch),
                typeof(bool),
                typeof(EnjoySelector),
                new PropertyMetadata(true));

        private static readonly DependencyProperty SleFontSizeProperty =
            DependencyProperty.Register(
                nameof(SleFontSize),
                typeof(double),
                typeof(EnjoySelector),
                new PropertyMetadata(15.0));

        private static readonly DependencyProperty SleIconFontSizeProperty =
            DependencyProperty.Register(
                nameof(SleIconFontSize),
                typeof(double),
                typeof(EnjoySelector),
                new PropertyMetadata(18.0));

        private static readonly DependencyProperty ItemsSourceProperty =
            DependencyProperty.Register(
                nameof(ItemsSource),
                typeof(IEnumerable),
                typeof(EnjoySelector),
                new PropertyMetadata(null, ItemsSourceChangeEvent));

        private static readonly DependencyProperty ItemsSourcePairProperty =
            DependencyProperty.Register(
                nameof(ItemsSourcePair),
                typeof(Dictionary<SelectorContentStruct, ObservableCollection<SelectorContentStruct>>),
                typeof(EnjoySelector),
                new PropertyMetadata(new Dictionary<SelectorContentStruct, ObservableCollection<SelectorContentStruct>>()));

        private static readonly DependencyProperty ApplyItemsSourceProperty =
            DependencyProperty.Register(
                nameof(ApplyItemsSource),
                typeof(IEnumerable),
                typeof(EnjoySelector),
                new PropertyMetadata(null));

        private static readonly DependencyProperty SelectedValueProperty =
            DependencyProperty.Register(
                nameof(SelectedValue),
                typeof(ObservableCollection<string>),
                typeof(EnjoySelector),
                new PropertyMetadata(new ObservableCollection<string>(), SelectedValueChangeEvent));

        private static readonly DependencyProperty SelectionPushCommandProperty = 
            DependencyProperty.Register(
            nameof(SelectionPushCommand),
            typeof(ICommand),
            typeof(EnjoySelector),
            new PropertyMetadata(null));

        public ICommand? SelectionChangeStdin;

        public ICommand SelectionPushCommand
        {
            get => (ICommand)GetValue(SelectionPushCommandProperty);
            set => SetValue(SelectionPushCommandProperty, value);
        }

        public ICommand SelectionChangeCommand
        {
            set
            {
                SelectionChangeStdin = value;
            }
            get
            {
                SelectionChangeStdin ??= new EasyCommand(SelectionChangeEvent, bool () => true);
                return SelectionChangeStdin;
            }
        }

        // 如果按钮不在选择状态，恢复默认的选项
        public static void PreViewMouseUpEvent(object? sender, MouseButtonEventArgs e)
        {
            if (sender is not null and EnjoySelector self)
            {
                if (self.IsChecked is not null and bool _IsChecked && !_IsChecked)
                {
                    self.ApplyItemsSource = self.ItemsSource;
                    self.SelectedValueJoin = [];
                }
            }
        }

        public void SelectionChangeEvent(object? param)
        {
            if (param is not null)
            {
                int SelectedIndex = int.Parse(param.GetSafetyChar());
                if (ApplyItemsSource is ObservableCollection<SelectorContentStruct> StepSelects)
                {
                    if (SelectedIndex >= 0 && SelectedIndex < StepSelects.Count)
                    {
                        SelectorContentStruct SelectionStep = StepSelects[SelectedIndex];
                        SelectedValueJoin.Add(SelectionStep.Name); //ready to combination selectedsObject reference not set to an instance of an object.”


                        if (StepContainFromSecondaryPair(SelectionStep, ItemsSourcePair, out var validStep) &&
                            validStep is not null)
                        {
                            ApplyItemsSource = validStep;
                        }
                        else
                        {
                            SelectedValue.Clear();
                            SelectedValue.AddRange(SelectedValueJoin);
                            SelectionPushCommand?.Execute(SelectedValueJoin);
                            if (ContentChangeSwitch && ActivityAssistBehivor.Behivor.ProductFixedOpptions.Count(x=> SelectedValueJoin.Join("").Contains(x)) == 0)
                            {
                                Content = SelectedValueJoin.Join(" · ");
                            }
                            ApplyItemsSource = ItemsSource;
                            SelectedValueJoin.Clear();
                            IsChecked = false;
                        }
                    }
                }
            }
        }

        public void WindowDeactiveEventTrigger(object? sender, EventArgs e)
        {
            IsChecked = false;
        }

        public void WindowClosedEventTrigger(object? sender, EventArgs e)
        {
            if (sender is not null and Window window)
            {
                window.Deactivated -= WindowDeactiveEventTrigger;
                window.Closed -= WindowClosedEventTrigger;
                WeakEventManager<ToggleButton, MouseButtonEventArgs>.RemoveHandler(this, nameof(ToggleButton.PreviewMouseUp), PreViewMouseUpEvent);
            }
            IsChecked = false;
        }

        public static void ItemsSourceChangeEvent(DependencyObject sender, DependencyPropertyChangedEventArgs e)
        {
            if (sender is not null and EnjoySelector self)
            {
                self.ApplyItemsSource = self.ItemsSource;
            }
        }

        private bool StepContainFromSecondaryPair(SelectorContentStruct option,
                                                  Dictionary<SelectorContentStruct, ObservableCollection<SelectorContentStruct>> targets,
                                                  out ObservableCollection<SelectorContentStruct>? ValidStepStruct)
        {
            foreach (var pair in targets)
            {
                if (pair.Key.Name == option.Name)
                {
                    ValidStepStruct = pair.Value;
                    return true;
                }
            }
            ValidStepStruct = null;
            return false;
        }

        private static void SelectedValueChangeEvent(DependencyObject sender, DependencyPropertyChangedEventArgs e)
        {
            if (sender is not null and EnjoySelector self &&
                e.NewValue is ObservableCollection<string> values &&
                self.ContentChangeSwitch)
            {

                if (values.Count == 1)
                {
                    self.Content = values[0];
                }
                else if (values.Count > 1)
                {
                    self.Content = values.Join(" · ");
                }
            }
        }

    }

    public class EnjoyMultilLayoutListBox : ListBox, IDisposable
    {
        private WeakReference<Control> WeakRefs;
        private static readonly ILogger Logger = Log.ForContext<EnjoyMultilLayoutListBox>();
        private readonly string AttributeKey = "combobox_Attribute_key";
        private readonly string MapTValueKey = "combobox_value_key";
        private readonly string MainGridKey = "grid_primary_content_key";
        private readonly List<string> ValidAtrributes = [];
        private BindingList<MultilAtrributeStruct> StandInAtrributes = [];
        
        private static readonly ConditionalWeakTable<UIElement, ConnectFlag> SubscriptionKeyvaluePair = [];

        public static void MvvmMessageProcessPlant(object recipient, MvvmMessage message)
        {
           switch (message.Type)
            {
                case MvvmMessage.MvvmType.Product_StepAddtion:
                    AddMultilAtrributeStep(recipient, message);
                    break;

                case MvvmMessage.MvvmType.Product_ArrestInfoGroupSet:
                    ArrestMultilAtrributeGroup(recipient, message);
                    break;

                case MvvmMessage.MvvmType.Product_StepSend:
                    SourceChangesEvent(recipient, message);
                    break;
            }
        }

        // 获取属性数据组
        public static void ArrestMultilAtrributeGroup(object recipient, MvvmMessage message)
        {
            EnjoyMultilLayoutListBox self = (EnjoyMultilLayoutListBox)recipient;
            self.Dispatcher.Invoke(() =>
            {
                List<MultilAtrributeStruct> AtrributesCombination = [];
                //遍历所有项
                foreach (ListBoxItem item in self.Items)
                {
                    
                    //获取主布局
                    if (item.Content is Grid mainGrid)
                    {
                        List<Grid> Grids = [.. mainGrid.FindVisualUpObjects<Grid, Grid>().Where(x => x.Name == self.MainGridKey)];
                        //遍历主布局所有行
                        if (Grids.Count == 1)
                        {
                            MultilAtrributeStruct attribute = new(string.Empty); //空属性
                            Grid contentGrid = Grids.First();
                            int rowCount = contentGrid.RowDefinitions.Count;
                            for (int row = 0; row < rowCount; row++)
                            {
                                var data = contentGrid.GetGridRowPairWidget<ComboBox, ComboBox>(row, self.AttributeKey, self.MapTValueKey);
                                if (data is not null)
                                {
                                    string RealKey = data.Value.Key.Text;
                                    string RealValue = data.Value.Value.Text;
                                    string? TreanslationKey = ActivityAssistBehivor.Behivor.fieldTranslationMap.GetSafetyKey(RealKey);
                                    if (!string.IsNullOrEmpty(TreanslationKey) &&
                                        attribute.GetField(TreanslationKey) is not null and FieldInfo expectField &&
                                        expectField.CanSafetyConvert(RealValue, out object? value))
                                    {
                                        expectField.SetValue(attribute, value);
                                    }
                                    else
                                    {
                                        Logger.DebudElite("content mybe empty or convert fail");
                                    }
                                }
                            }
                            AtrributesCombination.Add(attribute);
                        }
                    }
                }
                WeakReferenceMessenger.Default.Send<MvvmMessage>(new MvvmMessage(MvvmMessage.MvvmType.Product_ArrestInfoGroupOut, AtrributesCombination));
            });
        }

        public static void AddMultilAtrributeStep(object recipient, MvvmMessage message)
        {
            EnjoyMultilLayoutListBox self = (EnjoyMultilLayoutListBox)recipient;
            self.StandInAtrributes.RaiseListChangedEvents = false;
            self.StandInAtrributes.Clear(); // 源数据已形成，此时清空重新累加
            self.StandInAtrributes.Add(new ActivitySectionModel.MultilAtrributeStruct(" ", " ", " ", " "));
            self.StandInAtrributes.RaiseListChangedEvents = true;
            self.StandInAtrributes.ResetBindings();
        }

        public static async void SourceChangesEvent(object recipient, MvvmMessage message)
        {
            if (message.MsgBody is ObservableCollection<MultilAtrributeStruct> AtrributeSources && AtrributeSources.Count > 0 &&
                recipient is not null and EnjoyMultilLayoutListBox self)
            {
                await self.Dispatcher.InvokeAsync(async () =>
                {
                    try
                    {
                        self.StandInAtrributes.RaiseListChangedEvents = false;

                        while (true)
                        {
                            if (self.IsLoaded && self.Visibility == Visibility.Visible)
                            {
                                self.Items.Clear();
                                self.StandInAtrributes.Clear();
                                break;
                            }
                            await Task.Delay(1000);
                        }

                        self.StandInAtrributes.AddRange(AtrributeSources);

                        self.StandInAtrributes.RaiseListChangedEvents = true;

                        self.StandInAtrributes.ResetBindings();
                    } catch (Exception error)
                    {
                        Logger.ErrorElite(self, "", error.Message);
                    }
                });
            }
        }

        public static void StandinCollectionChange(EnjoyMultilLayoutListBox self, object? sender, ListChangedEventArgs e)
        {
            if (sender is not null && sender is BindingList<MultilAtrributeStruct> standins)
            {
                foreach (MultilAtrributeStruct attribute in standins)
                {
                    Application.Current.Dispatcher.Invoke(() =>
                    {
                        int row = 0;
                        self.ValidAtrributes.Clear();
                        Grid ItemGrid = new()
                        {
                            Name = self.MainGridKey,
                            VerticalAlignment = VerticalAlignment.Stretch,
                            HorizontalAlignment = HorizontalAlignment.Stretch
                        };

                        ItemGrid.ColumnDefinitions.Add(new ColumnDefinition { Width = new GridLength(4, GridUnitType.Star) });
                        ItemGrid.ColumnDefinitions.Add(new ColumnDefinition { Width = new GridLength(6, GridUnitType.Star) });
                        ItemGrid.ColumnDefinitions.Add(new ColumnDefinition { Width = new GridLength(1, GridUnitType.Star) });

                        Grid ItemOutGrid = new()
                        {
                            UseLayoutRounding = true,
                            VerticalAlignment = VerticalAlignment.Stretch,
                            HorizontalAlignment = HorizontalAlignment.Stretch,
                        };

                        ItemOutGrid.RowDefinitions.Add(new RowDefinition { Height = new GridLength(1, GridUnitType.Star) });
                        ItemOutGrid.RowDefinitions.Add(new RowDefinition { Height = new GridLength(43) });
                        ListBoxItem listBoxItem = new()
                        {
                            Margin = new Thickness(5),
                            BorderThickness = new Thickness(4),
                            HorizontalContentAlignment = HorizontalAlignment.Stretch,
                            VerticalContentAlignment = VerticalAlignment.Stretch
                        };

                        if ("DynamicListBoxItemControl".FindSource<ControlTemplate>() is not null and ControlTemplate template) listBoxItem.Template = template;

                        listBoxItem.BorderBrush = "RoyalSignal".FindSolidBrush();

                        foreach (var field in attribute.GetFields(1))
                        {
                            if (!ActivityAssistBehivor.Behivor.fieldHideds.Contains(field.Name))
                            {
                                self.ListBoxItemContentFull(ref ItemGrid, field.GetValue(attribute), field);
                            }
                            row++;
                        }

                        Grid bottonGrid = new()
                        {
                            Margin = new Thickness(0, 8, 0, 8),
                        };

                        bottonGrid.ColumnDefinitions.Add(new ColumnDefinition { Width = new GridLength(2, GridUnitType.Star) });
                        bottonGrid.ColumnDefinitions.Add(new ColumnDefinition { Width = new GridLength(4, GridUnitType.Star) });
                        bottonGrid.ColumnDefinitions.Add(new ColumnDefinition { Width = new GridLength(4, GridUnitType.Star) });

                        int itemIndex = 1;
                        itemIndex += self.Items.Count;
                        TextBlock DescBlock = new ()
                        {
                            Text = itemIndex.GetSafetyChar(),
                            Foreground = "MoonlitLavender".FindSolidBrush(),
                            FontSize = 16,
                            VerticalAlignment = VerticalAlignment.Center,
                            TextAlignment = TextAlignment.Center
                        };

                        Border DescBorder = new()
                        {
                            Width = 25.0,
                            Height = 25.0,
                            BorderThickness = new Thickness(0),
                            CornerRadius = new CornerRadius(12),
                            Background = "RoyalSignal".FindSolidBrush(),
                            Child = DescBlock,
                            VerticalAlignment = VerticalAlignment.Center
                        };

                        VariantButton AddtionParaghic = new()
                        {
                            MaxHeight = 35,
                            MaxWidth = 130,
                            FontSize = 15,
                            Content = "添加属性",
                            ForegroundColor = "OverBlack".FindSolidBrush(),
                            HorizontalAlignment = HorizontalAlignment.Stretch,
                            VerticalAlignment = VerticalAlignment.Stretch
                        };

                        VariantButton RemoveParaghic = new()
                        {
                            MaxHeight = 35,
                            MaxWidth = 130,
                            FontSize = 15,
                            Content = "删除属性",
                            ForegroundColor = "OverBlack".FindSolidBrush(),
                            HorizontalAlignment = HorizontalAlignment.Stretch,
                            VerticalAlignment = VerticalAlignment.Stretch
                        };

                        bottonGrid.SetGridWidget(0, 0, DescBorder);
                        bottonGrid.SetGridWidget(0, 1, AddtionParaghic);
                        bottonGrid.SetGridWidget(0, 2, RemoveParaghic);

                        ConnectFlag AddtionContainer = SubscriptionKeyvaluePair.GetOrCreateValue(AddtionParaghic);
                        if (!AddtionContainer.IsConnected)
                        {
                            WeakEventManager<Button, MouseButtonEventArgs>.AddHandler(AddtionParaghic, nameof(Button.PreviewMouseUp), ListBoxChildreanAddtion);
                            AddtionContainer.IsConnected = true;
                        }

                        ConnectFlag RemoveContainer = SubscriptionKeyvaluePair.GetOrCreateValue(RemoveParaghic);
                        if (!RemoveContainer.IsConnected)
                        {
                            WeakEventManager<Button, MouseButtonEventArgs>.AddHandler(RemoveParaghic, nameof(Button.PreviewMouseUp), ListBoxChildreanRemove);
                            RemoveContainer.IsConnected = true;
                        }

                        ItemOutGrid.SetGridWidget(0, 0, ItemGrid);
                        ItemOutGrid.SetGridWidget(1, 0, bottonGrid);

                        listBoxItem.BorderThickness = new Thickness(2);
                        listBoxItem.Content = ItemOutGrid;
                        self.Items.Add(listBoxItem);

                    });
                }
            }
        }

        public static void ListBoxChildreanAddtion(object? sender, MouseButtonEventArgs e)
        {
            DependencyObject dependencyObject = (DependencyObject)e.Source;
            if (dependencyObject.FindVisualUpObject<ListBoxItem>() is not null and ListBoxItem applyItem &&
                dependencyObject.FindVisualUpObject<EnjoyMultilLayoutListBox>() is not null and EnjoyMultilLayoutListBox self)
            {
                int indexOf = self.ItemContainerGenerator.IndexFromContainer(applyItem);
                Grid? ItemGrid = applyItem.FindVisualBtObject<Grid>(); //查找主布局
                List<Grid>? Grids = ItemGrid?.FindVisualUpObjects<Grid, Grid>(); //查找主布局下的Grid子布局
                Grid? realChildGrid = null;
                if (Grids is not null)
                {
                    foreach (Grid grid in Grids)
                    {
                        if (grid is not null && grid.Name == self.MainGridKey)
                        {
                            realChildGrid = grid;
                            break;
                        }
                    }
                }

                if (realChildGrid is not null) 
                {
                    self.ListBoxItemContentFull(
                        ref realChildGrid,
                        null,
                        null,
                        true);
                    applyItem.UpdateLayout();
                }
            }
        }

        public static void ListBoxChildreanRemove(object? sender, MouseButtonEventArgs e)
        {
            DependencyObject dependencyObject = (DependencyObject)e.Source;
            if (dependencyObject.FindVisualUpObject<ListBoxItem>() is not null and ListBoxItem applyItem &&
                dependencyObject.FindVisualUpObject<EnjoyMultilLayoutListBox>() is not null and EnjoyMultilLayoutListBox self)
            {
                self.Items.RemoveAt(self.ItemContainerGenerator.IndexFromContainer(applyItem));
            }
        }

        public void ListBoxItemContentFull(ref Grid layout, object? value, FieldInfo? fieldinfo, bool asolutePardon = false)
        {
            layout.RowDefinitions.Add(new RowDefinition { Height = GridLength.Auto });
            ComboBox AttributeBox = new()
            {
                FontSize = 15,
                Name = AttributeKey,
                FontFamily = "KaiTi".FindSource<FontFamily>(),
                ItemsSource = ActivityAssistBehivor.Behivor.fieldTranslationMap.Values,
                Margin = new Thickness(0, 8, 0, 8),
                HorizontalAlignment = HorizontalAlignment.Stretch,
                VerticalAlignment = VerticalAlignment.Stretch
            };

            ComboBox IdeaValueBox = new()
            {
                FontSize = 15,
                IsEditable = true,
                Name = MapTValueKey,
                FontFamily = "KaiTi".FindSource<FontFamily>(),
                Margin = new Thickness(0, 8, 10, 8),
                HorizontalAlignment = HorizontalAlignment.Stretch,
                VerticalAlignment = VerticalAlignment.Stretch,
                HorizontalContentAlignment = HorizontalAlignment.Stretch
            };

            TextBlock TakeTextBlock = new()
            {
                Text = "\ue61b",
                Name = MapTValueKey,
                FontFamily = "Icon".FindSource<FontFamily>(),
                FontSize = 20.0,
                Foreground = "SunsetCoral".FindSolidBrush(),
                Margin = new Thickness(10, 8, 0, 8),
                HorizontalAlignment = HorizontalAlignment.Stretch,
                VerticalAlignment = VerticalAlignment.Center
            };

            ConnectFlag AtrributeBoxConnectFlag = SubscriptionKeyvaluePair.GetOrCreateValue(AttributeBox);
            if (!AtrributeBoxConnectFlag.IsConnected)
            {
                WeakEventManager<ComboBox, SelectionChangedEventArgs>.AddHandler(AttributeBox, nameof(ComboBox.SelectionChanged), BoxSelectionChange);
                AtrributeBoxConnectFlag.IsConnected = true;
            }

            ConnectFlag IdeaValueBoxConnectFlag = SubscriptionKeyvaluePair.GetOrCreateValue(IdeaValueBox);
            if (!IdeaValueBoxConnectFlag.IsConnected)
            {
                WeakEventManager<ComboBox, SelectionChangedEventArgs>.AddHandler(IdeaValueBox, nameof(ComboBox.SelectionChanged), BoxSelectionChange);
                WeakEventManager<ComboBox, RoutedEventArgs>.AddHandler(IdeaValueBox, nameof(ComboBox.GotFocus), IdeaValueBoxFocusCHnage);
                IdeaValueBoxConnectFlag.IsConnected = true;
            }

            ConnectFlag TakeBlockConnectFlag = SubscriptionKeyvaluePair.GetOrCreateValue(TakeTextBlock);
            if (!TakeBlockConnectFlag.IsConnected)
            {
                WeakEventManager<TextBlock, MouseButtonEventArgs>.AddHandler(TakeTextBlock, nameof(TextBlock.PreviewMouseDown), TakeFromGridEncordingRow);
                TakeBlockConnectFlag.IsConnected = true;
            }

            if (!asolutePardon)
            {
  
                if (fieldinfo is not null && ActivityAssistBehivor.Behivor.fieldTranslationMap.TryGetValue(fieldinfo.Name, out string? translations))
                {
                    AttributeBox.Text = translations;
                    ValidAtrributes.Add(translations);
                }

                if (fieldinfo is not null && ActivityAssistBehivor.Behivor.fieldIsPrimaryMap.TryGetValue(fieldinfo.Name, out bool primary) && primary)
                {
                    AttributeBox.IsEnabled = !primary;
                    TakeTextBlock.Visibility = Visibility.Collapsed;
                }

                if (fieldinfo is not null && ActivityAssistBehivor.Behivor.fieldExepctPushMap.TryGetValue(fieldinfo.Name, out List<string>? exepcts))
                {
                    if (exepcts != null) IdeaValueBox.ItemsSource = exepcts;
                }
                if (value is not null)
                {
                    IdeaValueBox.Text = value.GetSafetyChar();
                }
            }
            
            layout.SetGridWidget(layout.RowDefinitions.Count - 1, 0, AttributeBox);
            layout.SetGridWidget(layout.RowDefinitions.Count - 1, 1, IdeaValueBox);
            layout.SetGridWidget(layout.RowDefinitions.Count - 1, 2, TakeTextBlock);
        }
        
        private static void IdeaValueBoxFocusCHnage(object? sender, RoutedEventArgs args)
        {
            if (sender is not null and ComboBox valueCombobox)
            {
                valueCombobox.Dispatcher.InvokeAsync(() =>
                {
                    if (sender is not null && sender is ComboBox IdeaValueBox)
                    {
                        if (IdeaValueBox.FindNestVisualTreeObject<TextBox>("PART_EditableTextBox") is not null and TextBox valueTextBox)
                        {
                            ConnectFlag IdeaValueBoxConnectFlag = SubscriptionKeyvaluePair.GetOrCreateValue(valueTextBox);
                            if (!IdeaValueBoxConnectFlag.IsConnected)
                            {
                                WeakEventManager<TextBox, TextChangedEventArgs>.AddHandler(valueTextBox, nameof(TextBox.TextChanged), TextBoxContentChange);
                                IdeaValueBoxConnectFlag.IsConnected = true;
                            }
                        }
                    }
                });
            }
        }

        private static void BoxSelectionChange(object? sender, SelectionChangedEventArgs e)
        {
            if (sender is not null)
            {
                ComboBox comboxbox = (ComboBox)sender;
                EnjoyMultilLayoutListBox? self = comboxbox.FindVisualUpObject<EnjoyMultilLayoutListBox>();
                comboxbox.Dispatcher.Invoke(async () =>
                {

                    DependencyObject boboxDependencyObject = (DependencyObject)e.Source;
                    Grid? mainGrid = boboxDependencyObject.FindVisualUpObject<Grid>();
                    ListBoxItem? listBoxItem = boboxDependencyObject.FindVisualUpObject<ListBoxItem>();
                    

                    try
                    {
                        if (self is not null && comboxbox.Name == self.AttributeKey && mainGrid is not null and Grid grid)
                        {
                            int currentIndex = Grid.GetRow(comboxbox);
                            List<UIElement> unitRow = grid.GetGridRowWidget(currentIndex);
                            ComboBox? valueComboBox = null;
                            foreach (var uiCom in unitRow)
                            {
                                
                                if (uiCom is ComboBox comboBox &&
                                    comboBox.Name == self.MapTValueKey) 
                                {
                                    valueComboBox = comboBox;
                                    if (comboxbox.SelectedValue is not null and string sltext &&
                                        ActivityAssistBehivor.Behivor.fieldTranslationMap.GetSafetyKey<string, string>(sltext) is not null and string key &&
                                        ActivityAssistBehivor.Behivor.fieldExepctPushMap.TryGetValue(key, out List<string>? exepcts))
                                    {
                                        if (exepcts != null)
                                        {
                                            await Task.Delay(10);
                                            comboBox.Dispatcher.Invoke(() =>
                                            {
                                                comboBox.ItemsSource = exepcts;
                                            });
                                            break;
                                        }
                                    }
                                }
                            }
                        }
                    }
                    catch (Exception error)
                    {
                        Logger.Error(error.Message);
                    }
                });
            }
        }

        private static void TextBoxContentChange(object? sender, TextChangedEventArgs e)
        {
            try
            {
                if (sender is not null)
                {
                    TextBox TxBox = (TextBox)sender;
                    TxBox.Dispatcher.InvokeAsync(() =>
                    {
                        EnjoyMultilLayoutListBox? self = TxBox.FindVisualUpObject<EnjoyMultilLayoutListBox>();
                        ComboBox? TxcomBox = TxBox.FindVisualUpObject<ComboBox>();
                        if (TxcomBox is not null && self is not null)
                        {
                            if (TxcomBox.FindVisualUpObject<Grid>() is not null and Grid mainLayoutGrid)
                            {
                                if (mainLayoutGrid.GetGridRowWidget(Grid.GetRow(TxcomBox)).GetWidget<ComboBox>(self.AttributeKey) is not null and ComboBox AtrributeBox)
                                {
                                    string? TranslationText = ActivityAssistBehivor.Behivor.fieldTranslationMap.GetSafetyKey<string, string>(AtrributeBox.Text);

                                    if (TranslationText is not null)
                                    {
                                        FieldInfo? field = new MultilAtrributeStruct(string.Empty).GetField(TranslationText);
                                        TxBox.Dispatcher.BeginInvoke(() =>
                                        {
                                            if (field is not null)
                                            {
                                                var TxBoxBorder = TxcomBox.FindVisualBtObject<Border>();
                                                if (field.CanSafetyConvert(TxBox.Text, out object? value))
                                                {
                                                    if (TxBoxBorder is not null)
                                                    {
                                                        TxBoxBorder.BorderBrush = SystemColors.ControlDarkBrush;
                                                        TxBoxBorder.BorderThickness = new Thickness(0);
                                                    }
                                                }
                                                else
                                                {
                                                    if (TxBoxBorder is not null)
                                                    {
                                                        TxBoxBorder.BorderBrush = "SunsetCoral".FindSolidBrush();
                                                        TxBoxBorder.BorderThickness = new Thickness(1);
                                                    }
                                                }
                                            }
                                        });
                                    }
                                }
                            }
                        }
                    });
                }
            }
            catch (Exception error)
            {
                Logger.Debug(error.Message);
            }
        }

        private static void TakeFromGridEncordingRow(object? sender, MouseButtonEventArgs e)
        {
            if (sender is not null && 
                sender is TextBlock textBlock &&
                textBlock.FindVisualUpObject<EnjoyMultilLayoutListBox>() is not null and EnjoyMultilLayoutListBox self &&
                textBlock.FindVisualUpObject<ListBoxItem>() is not null and ListBoxItem listBoxitem &&
                listBoxitem.Content is Grid mainGrid)
            {
                List<Grid> Grids = [..mainGrid.FindVisualUpObjects<Grid, Grid>().Where(x => x.Name == self.MainGridKey)];
                textBlock.Dispatcher.InvokeAsync(() =>
                {
                    try
                    {
                        if (Grids.Count > 0)
                        {
                            Grid ContentGrid = Grids[0];
                            int row = Grid.GetRow(textBlock);
                            List<UIElement> elements = ContentGrid.GetGridRowWidget(row);
                            foreach (var element in elements)
                            {
                                ContentGrid.Children.Remove(element);
                            }
                            ContentGrid.RowDefinitions.RemoveAt(row);
                            for (int surplus = row; surplus < ContentGrid.RowDefinitions.Count; surplus++)
                            {
                                List<UIElement> surplus_elements = ContentGrid.GetGridRowWidget(surplus);
                                foreach (var element in surplus_elements)
                                {
                                    if (element is not null)
                                    {
                                        Grid.SetRow(element, surplus);
                                    }
                                }
                            }
                        }
                    } catch (Exception error)
                    {
                        Logger.DebudElite($"attribute line remove encount error: {error.Message}");
                    }
                });
                
            }
        }

        private readonly object _syncobj = new();

        public bool _disposed = false;

        public void Dispose()
        {
            Dispose(true);
            GC.SuppressFinalize(this);
        }

        protected virtual void Dispose(bool disposing)
        {
            bool _synclock = false;
            try
            {
                if (!_disposed)
                {
                    Monitor.Enter(_syncobj, ref _synclock);
                    _disposed = true;
                }
            }
            finally
            {
                Logger.Debug($"{this} -> release, where lock stat {_synclock}");
                if (_synclock) Monitor.Exit(_syncobj);
            }
        }

        ~EnjoyMultilLayoutListBox()
        {
            Dispose(false);
        }

        private void OnLoader(object? sender, RoutedEventArgs e)
        {
            Dispose();
        }

        public EnjoyMultilLayoutListBox()
        {
            if ("ListBoxTemplate".FindSource<Style>() is not null and Style style)
            {
                Style = style;
            }

            WeakRefs = new WeakReference<Control>(this);

            WeakEventManager<ListBox, RoutedEventArgs>.AddHandler(this, nameof(ListBox.Unloaded), OnLoader);
            WeakEventManager<BindingList<MultilAtrributeStruct>, ListChangedEventArgs>
                .AddHandler(StandInAtrributes,
                            nameof(BindingList<MultilAtrributeStruct>.ListChanged),
                            (sender, e) =>
                            {
                                if (WeakRefs.TryGetTarget(out Control? target) &&
                            target is not null and EnjoyMultilLayoutListBox self)
                                {
                                    StandinCollectionChange(self, sender, e);
                                }
                            });

            WeakReferenceMessenger.Default.Register<MvvmMessage>(this, MvvmMessageProcessPlant);
            ScrollViewer.SetVerticalScrollBarVisibility(this, ScrollBarVisibility.Auto);
            Unloaded += UnLoad;
        }

        public void UnLoad(object sender, RoutedEventArgs e)
        {
            WeakEventManager<ListBox, RoutedEventArgs>.RemoveHandler(this, nameof(ListBox.Unloaded), OnLoader);
            WeakEventManager<BindingList<MultilAtrributeStruct>, ListChangedEventArgs>
                .RemoveHandler(StandInAtrributes,
                            nameof(BindingList<MultilAtrributeStruct>.ListChanged),
                            (sender, e) =>
                            {

                                StandinCollectionChange(this, sender, e);

                            });
            Unloaded -= UnLoad;
        }
    }

    public class EnjoyReserveDutyMapLayoutListBox : ListBox, IDisposable
    {
        private static readonly ILogger Logger = Log.ForContext<EnjoyReserveDutyMapLayoutListBox>();
        private readonly string MapTKey = "combobox_key";
        private readonly string MapTValue = "combobox_value";
        private readonly string Empty = "无";
        private List<string> ConsultColumnNames = [];
        Dictionary<string, string> ConsultMapdetail = [];
        private readonly List<string> TranslationFieldNames = [];
        private static readonly ConditionalWeakTable<UIElement, ConnectFlag> SubscriptionKeyvaluePair = [];

        public EnjoyReserveDutyMapLayoutListBox()
        {
            if ("ListBoxTemplate".FindSource<Style>() is not null and Style style)
            {
                Style = style;
            }
            TranslationFieldNames = [.. ActivityAssistBehivor.Behivor.fieldReserveDutyMap.Values];

            WeakReferenceMessenger.Default.Register<MvvmMessage>(this, MvvmMessageProcessPlant);

        }

        public static void MvvmMessageProcessPlant(object recipient, MvvmMessage message)
        {
            EnjoyReserveDutyMapLayoutListBox self = (EnjoyReserveDutyMapLayoutListBox)recipient;
            switch (message.Type)
            {
                case MvvmMessage.MvvmType.Database_MapInfoGroup_Request:
                    ArrestDBReserveMapGroup(recipient, message);
                    break;

                case MvvmMessage.MvvmType.Database_MapFilesSend:
                    GetInitializeDatas(recipient, message);
                    break;
            }
        }

        public static void GetInitializeDatas(object recipient, MvvmMessage mvvmMessage)
        {
            EnjoyReserveDutyMapLayoutListBox self = (EnjoyReserveDutyMapLayoutListBox)recipient;

            self.Dispatcher.Invoke(() =>
            {

                if (mvvmMessage.MsgBody is not null and KeyValuePair<Dictionary<string, string>, List<string>> data)
                {
                    self.ConsultColumnNames = data.Value;

                    if (!self.ConsultColumnNames.Contains(self.Empty)) self.ConsultColumnNames.Add(self.Empty);

                    self.ConsultMapdetail = data.Key;

                    if (self.Items.Count >= 1)
                    {
                        self.ShallowLoader();
                    }
                    else
                    {
                        self.StandinCollectionChange();
                    } 
                }
            });
        }

        public async static void ArrestDBReserveMapGroup(object recipient, MvvmMessage message)
        {
            EnjoyReserveDutyMapLayoutListBox self = (EnjoyReserveDutyMapLayoutListBox)recipient;
            await Task.Run(() =>
            {
                self.Dispatcher.Invoke(() =>
                {
                    Dictionary<string, string> TreamslationCombination = [];
                    foreach (ListBoxItem item in self.Items)
                    {
                        if (item.Content is Grid mainGrid)
                        {
                            for (int mrow = 0; mrow < mainGrid.RowDefinitions.Count; mrow++)
                            {
                                var ComponentPair = mainGrid.GetGridRowPairWidget<TextBlock, ComboBox>(mrow, self.MapTKey, self.MapTValue);


                                if (ComponentPair.HasValue)
                                {
                                    string RealKey = ComponentPair.Value.Key.Text;
                                    string RealValue = ComponentPair.Value.Value.Text;
                                    if (ActivityAssistBehivor.Behivor.fieldReserveDutyMap.GetSafetyKey<string, string>(RealKey) is not null and string transla &&
                                        !string.IsNullOrEmpty(RealValue))
                                    {
                                        TreamslationCombination.Add(transla, RealValue);
                                    }
                                }
                            }
                        }
                    }
                    WeakReferenceMessenger.Default.Send<MvvmMessage>(new MvvmMessage(MvvmMessage.MvvmType.Database_MapInfoGroup_Acquire, TreamslationCombination));
                });
            });
        }

        public async void ShallowLoader()
        {
            await Task.Run(() =>
            {
                Dispatcher.Invoke(() =>
                {
                    Dictionary<string, string> TreamslationCombination = [];
                    foreach (ListBoxItem item in Items)
                    {
                        if (item.Content is Grid mainGrid)
                        {
                            for (int mrow = 0; mrow < mainGrid.RowDefinitions.Count; mrow++)
                            {
                                var ComponentPair = mainGrid.GetGridRowPairWidget<TextBlock, ComboBox>(mrow, MapTKey, MapTValue);

                                if (ComponentPair is not null)
                                { 
                                    TextBlock TranslationBlock = ComponentPair.Value.Key;

                                    ComboBox IdeaColumnBox = ComponentPair.Value.Value;
                                
                                    if (ConsultMapdetail.Count > 0)
                                    {
                                        if (ActivityAssistBehivor.Behivor.fieldReserveDutyMap.GetSafetyKey(TranslationBlock.Text) is not null and string key &&
                                            ConsultMapdetail.TryGetValue(key, out string? value) && IdeaColumnBox is not null)
                                        {
                                            IdeaColumnBox.Text = value;
                                        }
                                    }
                                }
                            }
                        }
                    }
                });
            });
        }

        public void StandinCollectionChange()
        {
            Application.Current.Dispatcher.InvokeAsync(() =>
            {
                int row = 0;
                Grid ItemGrid = new()
                {
                    VerticalAlignment = VerticalAlignment.Stretch,
                    HorizontalAlignment = HorizontalAlignment.Stretch
                };

                ItemGrid.ColumnDefinitions.Add(new ColumnDefinition { Width = new GridLength(3, GridUnitType.Star) });
                ItemGrid.ColumnDefinitions.Add(new ColumnDefinition { Width = new GridLength(7, GridUnitType.Star) });

                ListBoxItem listBoxItem = new()
                {
                    Margin = new Thickness(5),
                    BorderThickness = new Thickness(4),
                    HorizontalContentAlignment = HorizontalAlignment.Stretch,
                    VerticalContentAlignment = VerticalAlignment.Stretch
                };

                if ("DynamicListBoxItemControl".FindSource<ControlTemplate>() is not null and ControlTemplate template) listBoxItem.Template = template;

                listBoxItem.BorderBrush = "RoyalSignal".FindSolidBrush();

                foreach (string translation in TranslationFieldNames)
                {
                    ListBoxItemContentFull(ItemGrid, translation);
                    row++;
                }

                listBoxItem.BorderThickness = new Thickness(2);
                listBoxItem.Content = ItemGrid;
                Items.Add(listBoxItem);
            }, DispatcherPriority.Background);
        }

        public void ListBoxItemContentFull(Grid layout, string translation)
        {
            this.Dispatcher.InvokeAsync(() =>
            {
                layout.RowDefinitions.Add(new RowDefinition { Height = GridLength.Auto });
                TextBlock TranslationName = new()
                {
                    Text = translation,
                    FontSize = 15,
                    Name = MapTKey,
                    FontFamily = "KaiTi".FindSource<FontFamily>(),
                    Margin = new Thickness(4, 6, 4, 6),
                    HorizontalAlignment = HorizontalAlignment.Center,
                    VerticalAlignment = VerticalAlignment.Stretch
                };

                ComboBox IdeaColumnBox = new()
                {
                    FontSize = 15,
                    IsEditable = true,
                    Name = MapTValue,
                    FontFamily = "KaiTi".FindSource<FontFamily>(),
                    ItemsSource = ConsultColumnNames,
                    Margin = new Thickness(4, 6, 4, 6),
                    HorizontalAlignment = HorizontalAlignment.Stretch,
                    VerticalAlignment = VerticalAlignment.Stretch,
                    HorizontalContentAlignment = HorizontalAlignment.Stretch
                };

                if (ConsultMapdetail.Count > 0)
                {
                    if (ActivityAssistBehivor.Behivor.fieldReserveDutyMap.GetSafetyKey(translation) is not null and string key &&
                        ConsultMapdetail.TryGetValue(key, out string? value))
                    {
                        IdeaColumnBox.Text = value;
                    }
                }

                ConnectFlag AtrributeBoxConnectFlag = SubscriptionKeyvaluePair.GetOrCreateValue(IdeaColumnBox);
                if (!AtrributeBoxConnectFlag.IsConnected)
                {
                    WeakEventManager<ComboBox, EventArgs>.AddHandler(IdeaColumnBox, nameof(ComboBox.DropDownOpened), ComboboxItemsChange);
                    AtrributeBoxConnectFlag.IsConnected = true;
                }

                layout.SetGridWidget(layout.RowDefinitions.Count - 1, 0, TranslationName);
                layout.SetGridWidget(layout.RowDefinitions.Count - 1, 1, IdeaColumnBox);
            }, DispatcherPriority.DataBind);
        }

        private async static void ComboboxItemsChange(object? sender, EventArgs args)
        {
            if (sender is not null and ComboBox _Combobox)
            {
                await Task.Run(async () =>
                {
                    await _Combobox.Dispatcher.InvokeAsync(async () =>
                    {
                        string Privious = _Combobox.Text;
                         EnjoyReserveDutyMapLayoutListBox? self = _Combobox.FindVisualUpObject<EnjoyReserveDutyMapLayoutListBox>();
                    
                        List<string> allComboboxText = [.. _Combobox.FindVisualUpObjects<Grid, ComboBox>().Select(x => x.Text)];
                        if (self is not null)
                        {
                            List<string> suplusTrans = [.. self.ConsultColumnNames.Where(x => !allComboboxText.Contains(x))];

                            if (!suplusTrans.Contains(self.Empty)) suplusTrans.Add(self.Empty);

                            _Combobox.ItemsSource = suplusTrans;
                        }

                        await Task.Delay(120);

                        _Combobox.Text = Privious;

                    });
                });
            }
        }

        private readonly object _syncobj = new();

        public bool _disposed = false;

        public void Dispose()
        {
            Dispose(true);
            GC.SuppressFinalize(this);
        }

        protected virtual void Dispose(bool disposing)
        {
            Dispatcher.Invoke(() =>
            {
                bool _synclock = false;
                try
                {
                    if (!_disposed)
                    {
                        Monitor.Enter(_syncobj, ref _synclock);
                        _disposed = true;
                    }
                }
                finally
                {
                    Logger.Debug($"{this} -> release, where lock stat {_synclock}");
                    if (_synclock) Monitor.Exit(_syncobj);
                }
            });
        }

        ~EnjoyReserveDutyMapLayoutListBox()
        {
            Dispose(false);
        }

        private void OnLoader(object? sender, RoutedEventArgs e)
        {
            Dispose();
        }
    }

    public class EnjoyToggleButton : ToggleButton
    {
        private readonly ILogger Logger = Log.ForContext<EnjoyToggleButton>();
        private static readonly ConditionalWeakTable<Control, ConnectFlag> SubscriptionKeyvaluePair = [];
        private List<string> SelectedValueJoin = [];

        public EnjoyToggleButton()
        {
            FontFamily = "YaHei".FindSource<FontFamily>() ?? new FontFamily("KaiTi");
            UseLayoutRounding = true;
        }

        
        public CornerRadius CornerRadius
        {
            set { SetValue(CornerRadiusProperty, value); }
            get { return (CornerRadius)GetValue(CornerRadiusProperty); }
        }

       

        public static readonly DependencyProperty CornerRadiusProperty =
            DependencyProperty.Register(
                nameof(CornerRadius),
                typeof(CornerRadius),
                typeof(EnjoyToggleButton),
                new PropertyMetadata(new CornerRadius(3)));

    }

    public class EnjoyCombobox : ComboBox
    {
        private DispatcherTimer ContentTimer = new DispatcherTimer();
        private int DelayContentMs = 1300;
        private string TextBoxContent = string.Empty;
        Stopwatch ContentWatch = Stopwatch.StartNew();
        WeakReference<TextBox>? reference;
        ConditionalWeakTable<Control, ConnectFlag> ConnectFlag = [];

        public EnjoyCombobox()
        {

            if (new FontFamilyConverter().ConvertFrom("Microsoft YaHei") is not null and FontFamily family)
            {
                FontFamily = family;
            }
            ContentWatch.Stop();
            ContentTimer.Interval = TimeSpan.FromSeconds(1.5);
            WeakEventManager<DispatcherTimer, EventArgs>.AddHandler(ContentTimer, nameof(DispatcherTimer.Tick), (obj, e) => { ContentTimerCheck(this, obj, e); });
            WeakEventManager<ComboBox, RoutedEventArgs>.AddHandler(this, nameof(ComboBox.Loaded), LoadedUI);
            WeakEventManager<ComboBox, RoutedEventArgs>.AddHandler(this, nameof(ComboBox.Unloaded), UnLoadedUI);
        }

        public static void LoadedUI(object? sender, RoutedEventArgs e)
        {
            if (sender is not null && sender is EnjoyCombobox self)
            {
                TextBox? textBox = self.FindVisualBtObject<TextBox>();
                if (textBox is not null)
                {
                    ConnectFlag connect = self.ConnectFlag.GetOrCreateValue(textBox);
                    if (!connect.IsConnected)
                    {
                        if (self.reference == null)
                        {
                            self.reference = new WeakReference<TextBox>(textBox);
                            self.reference.SetTarget(textBox);
                            textBox.Text = self.PlaceEchoderText;
                        }
                        WeakEventManager<TextBox, TextChangedEventArgs>.AddHandler(textBox, nameof(TextBox.TextChanged), TextChange);
                        WeakEventManager<TextBox, RoutedEventArgs>.AddHandler(textBox, nameof(TextBox.GotFocus), GotFocusChange);
                        WeakEventManager<TextBox, RoutedEventArgs>.AddHandler(textBox, nameof(TextBox.LostFocus), LostFocusChange);
                    }
                }
            }
        }

        public static void UnLoadedUI(object? sender, RoutedEventArgs e)
        {
            if (sender is not null && sender is EnjoyCombobox self)
            {
                WeakEventManager<ComboBox, RoutedEventArgs>.RemoveHandler(self, nameof(ComboBox.Loaded), LoadedUI);
                WeakEventManager<ComboBox, RoutedEventArgs>.RemoveHandler(self, nameof(ComboBox.Unloaded), UnLoadedUI);
                if (self.reference is not null && self.reference.TryGetTarget(out TextBox? textBox) &&
                    textBox is not null)
                {
                    WeakEventManager<TextBox, TextChangedEventArgs>.RemoveHandler(textBox, nameof(TextBox.TextChanged), TextChange);
                    WeakEventManager<TextBox, RoutedEventArgs>.RemoveHandler(textBox, nameof(TextBox.GotFocus), GotFocusChange);
                    WeakEventManager<TextBox, RoutedEventArgs>.RemoveHandler(textBox, nameof(TextBox.LostFocus), LostFocusChange);
                }
            }
        }

        public static void ContentTimerCheck(EnjoyCombobox self, object? sender, EventArgs e)
        {
            if (self.ContentWatch.ElapsedMilliseconds > self.DelayContentMs)
            {
                self.TextChangeCommand.Execute(self.TextBoxContent);
                self.ContentWatch.Stop();
                self.ContentTimer.Stop();
            }
        }

        public static void TextChange(object? sender, TextChangedEventArgs e)
        {
            if (sender is not null && 
                sender is TextBox _TextBox &&
                _TextBox.FindVisualUpObject<EnjoyCombobox>() is not null and EnjoyCombobox self) 
            {
                if (!self.ContentTimer.IsEnabled) self.ContentTimer.Start();
                self.ContentWatch.Restart();
                self.TextBoxContent = _TextBox.Text;
            }
        }

        public static void GotFocusChange(object? sender, RoutedEventArgs e)
        {
            if (sender is not null and TextBox _TextBox &&
                _TextBox.FindVisualUpObject<EnjoyCombobox>() is not null and EnjoyCombobox self &&
                _TextBox.Text == self.PlaceEchoderText)
            {
                _TextBox.Text = string.Empty;
            }
        }

        public static void LostFocusChange(object? sender, RoutedEventArgs e)
        {
            if (sender is not null and TextBox _TextBox &&
                _TextBox.FindVisualUpObject<EnjoyCombobox>() is not null and EnjoyCombobox self &&
                string.IsNullOrEmpty(_TextBox.Text))
            {
                _TextBox.Text = self.PlaceEchoderText;
            }
        }

        public static void PlaceEchoderChange(DependencyObject sender, DependencyPropertyChangedEventArgs e)
        {
            if (sender is not null and TextBox _TextBox &&
                _TextBox.FindVisualUpObject<EnjoyCombobox>() is not null and EnjoyCombobox self &&
                string.IsNullOrEmpty(_TextBox.Text))
            {
                _TextBox.Text = self.PlaceEchoderText;
            }
        }

        public string PlaceEchoderText
        {
            set { SetValue(EchoTextProperty, value); }
            get { return (string)GetValue(EchoTextProperty); }
        }

        public ICommand TextChangeCommand
        {
            get => (ICommand)GetValue(TextChangeCommandProperty);
            set => SetValue(TextChangeCommandProperty, value);
        }

        public static readonly DependencyProperty EchoTextProperty =
            DependencyProperty.Register(nameof(PlaceEchoderText), 
                                        typeof(string), 
                                        typeof(EnjoyCombobox),
                                        new PropertyMetadata(string.Empty, PlaceEchoderChange));

        private static readonly DependencyProperty TextChangeCommandProperty = DependencyProperty.Register(
            nameof(TextChangeCommand),
            typeof(ICommand),
            typeof(EnjoyCombobox),
            new PropertyMetadata(null));
    }
}
